• 纯js 实现 HTML 元素拖拽,


    let Drag = function () {
        function isElement(obj) {
            return (typeof HTMLElement === 'object')
                ? (obj instanceof HTMLElement)
                : !!(obj && typeof obj === 'object' && (obj.nodeType === 1 || obj.nodeType === 9) && typeof obj.nodeName === 'string');
        }
    
    
        let elements = document.getElementsByClassName("drag");
        for (let elementsKey in elements) {
            let element = elements[elementsKey];
            if (!isElement(element)) {
                continue;
            }
            drag(element);
        }
    
        function drag(element) {
            element.setAttribute("ondragstart", "return false");
            element.style.position = "relative";
            element.onmousedown = function (e) {
                this.setAttribute("drag", "true");
                this.setAttribute("x", e.x);
                this.setAttribute("y", e.y);
                this.setAttribute("t", isNaN(Number.parseInt(this.style.top)) ? 0 : Number.parseInt(this.style.top));
                this.setAttribute("l", isNaN(Number.parseInt(this.style.left)) ? 0 : Number.parseInt(this.style.left));
            }
            element.onmousemove = function (e) {
                if (this.getAttribute("drag") === "true") {
                    if (this.offsetLeft >= this.parentElement.offsetLeft ||
                        this.offsetLeft <= this.parentElement.offsetLeft + this.parentElement.offsetWidth ||
                        this.offsetTop >= this.parentElement.offsetTop ||
                        this.offsetTop <= this.parentElement.offsetTop + this.parentElement.offsetHeight
                    ) {
                        this.style.left = e.x - (Number.parseInt(this.getAttribute("x"))) + (Number.parseInt(this.getAttribute("l"))) + "px";
                        this.style.top = e.y - (Number.parseInt(this.getAttribute("y"))) + (Number.parseInt(this.getAttribute("t"))) + "px";
                    }
                }
            }
            element.onmouseup = function (e) {
                this.setAttribute("drag", "false");
                this.setAttribute("x", e.x);
                this.setAttribute("y", e.y);
            }
            element.onmouseout = function (e) {
                this.setAttribute("drag", "false");
            }
        }
    
        window.drag = drag;
    }();
    如何调用:
    
    第一种方式:在元素的class上添加 drag 。例如 <div class="drag"></div>
    第一种方式:drag(元素)。例如 drag($("div"));
  • 相关阅读:
    常看本地是否安装Git和maven工具
    Git 安装和使用Tips
    Jmeter 获取系统时间,和对系统时间进行增减时间
    Java 中的系统时间
    Go语言
    数据拆分之 垂直拆分 and 水平拆分
    在Windows和UNIX下利用PHP和LDAP进行身份验证
    Linux中使用crontab命令定时执行shell脚本或其他Linux命令
    php empty()和isset()的区别
    php 判断是否get传值的参数是否存在
  • 原文地址:https://www.cnblogs.com/gatico/p/14693620.html
Copyright © 2020-2023  润新知