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

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

  • 相关阅读:
    【转载】openCV轮廓操作
    求两个已排序数组的中位数
    朴素贝叶斯分类
    Different Ways to Add Parentheses
    QSerialPort
    opencv鼠标绘制直线 C++版
    Word Break
    C++中 指针 与 引用 的区别
    敲入url到浏览器后会发生什么
    Sort List 分类: leetcode 算法 2015-07-10 15:35 1人阅读 评论(0) 收藏
  • 原文地址:https://www.cnblogs.com/chao202426/p/14824808.html
Copyright © 2011-2022 走看看