JavaScript鼠标拖拽特效及相关问题总结

#div1{width:200px;height:200px;background:red;position:absolute;}
#div2{width:200px;height:200px;background:green;position:absolute;left:300px;}
<div >原来的  普通拖拽</div>
<div >继承的 限制范围拖拽</div>
window.onload=function()
{
    new Drag('div1');
    new LimitDrag('div2');
};

function Drag(id)
{
    this.disX=0;
    this.disY=0;
    var _this=this;
    this.oDiv=document.getElementById(id);
    
    this.oDiv.onmousedown=function(ev)
    {
        _this.fnDown(ev);
        return false;
    };
};

Drag.prototype.fnDown=function(ev)
{
    var _this=this;
    var oEvent=ev||event;
    
    this.disX=oEvent.clientX-this.oDiv.offsetLeft;
    this.disY=oEvent.clientY-this.oDiv.offsetTop;
    
    document.onmousemove=function(ev)
    {
        _this.fnMove(ev);
    };
    
    document.onmouseup=function()
    {
        _this.fnUp();
    };
};

Drag.prototype.fnMove=function(ev)
{
    var oEvent=ev||event;
    this.oDiv.style.left=oEvent.clientX-this.disX+'px';
    this.oDiv.style.top=oEvent.clientY-this.disY+'px';
};

Drag.prototype.fnUp=function()
{
    document.onmousemove=null;
    document.onmouseup=null;    
};

/*继承*/
function LimitDrag(id)
{
    Drag.call(this,id);
};

for(var i in Drag.prototype)
{
    LimitDrag.prototype[i]=Drag.prototype[i];
};

LimitDrag.prototype.fnMove=function (ev)
{
    var oEvent=ev||event;
    var l=oEvent.clientX-this.disX;
    var t=oEvent.clientY-this.disY;
    
    if(l<0)
    {
        l=0;
    }
    else if(l>document.documentElement.clientWidth-this.oDiv.offsetWidth)
    {
        l=document.documentElement.clientWidth-this.oDiv.offsetWidth;
    }
    
    this.oDiv.style.left=l+'px';
    this.oDiv.style.top=t+'px';
};

鼠标拖拽效果最容易出现几个问题:

1、元素脱离鼠标,原因是“鼠标不离开元素基本不可能,这跟浏览器解析速度有关,浏览器解析速度又跟CPU有关”,所以元素脱离鼠标是必然的,解决办法就是采用事件委托,把事件委托到document上,而不是需要拖拽的元素上,事件本身是会冒泡的,会触发委托在document上的事件

2、元素的left和top值不能简单的设置为event.clientX或者是event.clientY,必须考虑鼠标在元素上的位置,否则元素很容易脱离鼠标