zoukankan      html  css  js  c++  java
  • js简单实现拖拽功能

    html:

    <div class="mydiv1"></div>

    css:

    .mydiv1 {
        width: 100px;
        height: 100px;
        background: red;
        position: absolute;
    }

    js:

    let mydiv1 = document.querySelector(".mydiv1");
    mydiv1.onmousedown = e => {
        let ev = e || window.event;
        let x = ev.clientX - mydiv1.offsetLeft;
        let y = ev.clientY - mydiv1.offsetTop;
        mydiv1.onmousemove = e => {
            let ev = e || window.event;
            let xx = ev.clientX;
            let yy = ev.clientY;
            mydiv1.style.left = xx - x + "px";
            mydiv1.style.top = yy - y + "px";
        }
        mydiv1.onmouseup = function () {
            mydiv1.onmousemove = "";
        }
    }

    好像没什么毛病,基本功能是实现了。传统的面向过程编程,代码没有什么拓展性,就是一步一步的实现,

    同样这个案例,下面用面向对象的方法实现以下:

    function Drag(ele) {
        this.ele = ele;
        this.downFn();
    }
    Drag.prototype.downFn = function () {
        this.ele.onmousedown = e => {
            let ev = e || window.event;
            let x = ev.clientX - this.ele.offsetLeft;
            let y = ev.clientY - this.ele.offsetTop;
            this.moveFn(x, y);
            this.upFn();
        }
    }
    Drag.prototype.moveFn = function (x, y) {
        this.ele.onmousemove = e => {
            let ev = e || window.event;
            let xx = ev.clientX;
            let yy = ev.clientY;
            this.setStyle(xx - x, yy - y)
        }
    }
    Drag.prototype.upFn = function () {
        this.ele.onmouseup = () => {
            this.ele.onmousemove = "";
        }
    }
    Drag.prototype.setStyle = function (leftNum, topNum) {
        this.ele.style.left = leftNum + "px";
        this.ele.style.top = topNum + "px";
    }
    let mydiv1 = document.querySelector(".mydiv1");
    let drag1 = new Drag(mydiv1);

    这么一看的话,好像更加复杂了,但实际上更加灵活,面向对象编程,拆分越细,拓展越灵活。

  • 相关阅读:
    【01】markdown语法
    H5系列之地理位置(必知必会)
    【07】像使用命令行一样使用 GitHub URL
    【11】把 GitHub 当 CMS 用
    【01】在 issue 中创建 list
    【06】GitHub WiKi
    【05】project board
    7.10-11 visudo、sudo
    7.7-9 chage、chpasswd、su
    7.1 useradd:创建用户
  • 原文地址:https://www.cnblogs.com/chao202426/p/14824808.html
Copyright © 2011-2022 走看看