zoukankan      html  css  js  c++  java
  • 纯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"));
  • 相关阅读:
    MIT 6.828 JOS学习笔记10. Lab 1 Part 3: The kernel
    Java基础知识点4:继承
    CentOS Installation
    超微主板创建RAID磁盘阵列
    MySQL查询语句
    Psql操作命令
    Let's Encrypt 免费 SSL 证书续期
    Linux系统禁用swap分区
    公共 NTP 服务器地址
    Postgresql配置
  • 原文地址:https://www.cnblogs.com/gatico/p/14693620.html
Copyright © 2011-2022 走看看