javascript面向对象封装拖拽插件演示

简单封装一个拖拽插件,以面向对象方式实现,当然还有其他很多写法,这里简单做个笔记记录一下!

Css

.box {
    position: absolute;
    width: 100px;
    height: 100px;
    background: #f00;
}

Html

<div class="box"></div>

Javascript

(function(doc){
    /**
     * [Drag 拖拽]
     * @param {[type]} el [要拖拽的元素]
     * 使用方法:
     * new Drag('.box').init();
     */
    function Drag(el){
        this.el = el;
        this.elem = doc.querySelector(this.el);
        this.disX = 0;
        this.disY = 0;
        this.isMove = false; // 判断mouseup的开关,如为true才触发mousemove事件动作
    }

    Drag.prototype = {
        constructor: Drag,   // prototype{} 覆盖的方式,要手动将constructor引用指回Drag父类
        init: function() {
            var _that = this;
            _that.elem.addEventListener('mousedown', function(ev){
                _that.down(ev, _that);

                // mousemove和mouseup放这里而不放外面的原因是当鼠标按下要拖动的元素才触发拖拽动作
                doc.addEventListener('mousemove', function(ev){
                    _that.move(ev, _that);
                });
                doc.addEventListener('mouseup', function(){
                    _that.up(_that);
                });
            });
        },
        // 鼠标按下动作
        down: function(ev, _that) {
            var ev = ev || event;
            _that.disX = ev.pageX - _that.elem.offsetLeft;
            _that.disY = ev.pageY - _that.elem.offsetTop;
            _that.isMove = true;    // 开启开关
        },
        // 鼠标拖拽动作
        move: function(ev, _that) {
            var ev = ev || event;
            if(_that.isMove) { // 判断开关是否开启
                _that.elem.style.left = ev.pageX - _that.disX + 'px';
                _that.elem.style.top = ev.pageY - _that.disY + 'px';
            }
        },
        // 鼠标提起动作
        up: function(_that) {
            _that.isMove = false;   // 关闭开关
            console.log('up...');
        }
    }

    //暴露全局对象
    window.Drag = Drag;

})(document);

调用:

var _darg = new Drag('.box').init();
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容