Java Web前端学习笔记程序员

JS事件_拖拽封装

2016-11-17  本文已影响322人  小夫特

写在前面,初学者,共同进步 ,个人笔记分享

01


拖拽.gif

拖拽

网页中经常需要div的拖动,这里写的封装的一个函数是无限制的拖拽,可以在子类中添加各种限制条件,完成拖拽。

02


/**
 * @constructor
 * @param {String} id = id为盒子div的id
 * @description 拖拽
 * @example 
 * var myDrag = new Drag('id'); 
 */
function Drag(id) {
    this.disX = 0;
    this.disY = 0;
    var _this = this;
    this.oDiv = document.getElementById(id);
    
    //鼠标按下事件
    this.oDiv.onmousedown = function() {
        _this.Down();
        //阻止默认事件
        return false;
    };  
}

03方法


鼠标按下
//鼠标按下函数
Drag.prototype.Down = function(ev) {
    var _this = this;
    var oEvent = ev || event;
    //在鼠标按下的时候记录鼠标与div之间的横向纵向距离
    this.disX = oEvent.clientX - _this.oDiv.offsetLeft;
    this.disY = oEvent.clientY - _this.oDiv.offsetTop;
    
    //事件绑定 解决拖动文字被选中的问题
    if (this.oDiv.setCapture) {
        //IE
        this.oDiv.onmousemove =function(){
            _this.fnMove(ev);
        };
        this.oDiv.onmouseup = function(){
            _this.fnUp(this);
        };
        this.oDiv.setCapture();
    } else{
        document.onmousemove = function(ev) {
            _this.fnMove(ev);
        };
        document.onmouseup = function() {
            _this.fnUp(this);       
        };
    }
}
鼠标移动与抬起
//鼠标移动时根据鼠标的位置计算div的位置并实时更新位置
Drag.prototype.fnMove = function(ev) {
    var oEvent = ev || event;
    var left = oEvent.clientX - this.disX;
    var top = oEvent.clientY - this.disY;

    this.oDiv.style.left = left + 'px';
    this.oDiv.style.top = top + 'px';
}
//鼠标抬起来的时候释放鼠标移动以及抬起事件
Drag.prototype.fnUp = function(oAttr) {
    oAttr.onmousemove = null;
    oAttr.onmouseup = null;
      //需要释放捕获的事件
    if (oAttr.releaseCapture) {
        oAttr.releaseCapture();
    }
}

04 使用


new Drag( );

05 封装函数源码与小例子


js文件可直接引用
Drag.js 框架下载
运用的例子

上一篇 下一篇

猜你喜欢

热点阅读