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);

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

  • 相关阅读:
    poj 4005 Moles
    牛客 2C 圈圈
    牛客 2B 树 (组合计数)
    AC日记——校门外的树(增强版) 洛谷 P1276
    AC日记——寻找道路 洛谷 P2296
    AC日记——挤牛奶 洛谷 P1204
    AC日记——最大数 洛谷 P1198 [JSOI2008]
    AC日记——中位数 洛谷 P1168
    AC日记——校门外的树 洛谷 P1047
    AC日记——约瑟夫问题 codevs 1282
  • 原文地址:https://www.cnblogs.com/chao202426/p/14824808.html
Copyright © 2011-2022 走看看