代码改变世界

实现div拖拽

2013-11-08 15:40  taozsay  阅读(307)  评论(0)    收藏  举报

实现div拖拽需要三个重要的事件:

1、onmousedown-鼠标按下事件

2、onmousemove-鼠标移动事件

3、onmouseup-鼠标抬起事件

当鼠标移出浏览器后再回到浏览器内部时,会丢失对div的控制,需要再次按下鼠标移动div,为了改善这一小问题,代码中使用了setCapture和releaseCapture。

其中,setCapture方法是用于监视鼠标操作事件,即使鼠标移出浏览器照样能够捕捉到鼠标位置,当鼠标移回浏览器内部时,此时div依然跟随着鼠标移动;当然,releaseCapture方法就是释放对鼠标操作事件的监视。

直接上码:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>实现div拖拽</title>
<style>
    html{background: #002433}
    body,div,p{margin:0;padding:0}
    #box{height:220px;width:200px;border:1px solid #02212D;position: absolute;left:0;background: #fff}
    #handler{height:30px;background:#ddd;cursor: move;}
</style>
</head>

<body>
    <div id='box'>
        <p id='handler'></p>    
    </div>
</body>
</html>
<script>
    window.onload=function(){
    new drag('box','handler',true);
}

function drag(){return this.init.apply(this,arguments)};

drag.prototype={
    init: function(container,handler,isLimit){
        this.o=document.getElementById(container);
        this.h=document.getElementById(handler);
        this._x=this._y=0;
        this.limit = isLimit;
        this._move=this.bind(this,this.move); 
        this._end=this.bind(this,this.end);
        this.addEvent(this.h,'mousedown',this.bind(this,this.start));
    },

    start:function(e){
        var ev = e || window.event;
        this._x = ev.clientX - this.o.offsetLeft;
        this._y = ev.clientY - this.o.offsetTop;
        this.addEvent(document,'mousemove',this._move);
        this.addEvent(document,'mouseup',this._end);
        ev.preventDefault && ev.preventDefault();
        this.h.setCapture && this.h.setCapture();
    },

    move:function(e){
        var ev = e || window.event,
        l= ev.clientX - this._x,
        t= ev.clientY - this._y;
        if(!!this.limit){
            var maxX = document.documentElement.clientWidth - this.o.offsetWidth,
            maxY = document.documentElement.clientHeight - this.o.offsetHeight;
            l = l < 0 ? 0 : l;
            l = l > maxX ? maxX : l;
            t = t < 0 ? 0 : t;
            t = t >maxY ? maxY : t;
        }
        this.o.style.left = l +'px';
        this.o.style.top = t +'px';
    },

    end:function(){
        this.removeEvent(document,'mousemove',this._move);
        this.removeEvent(document,'mouseup',this._end);
        this.h.releaseCapture && this.h.releaseCapture(); 
    },

    addEvent:function(o,e,fn){
        return o.attachEvent ? o.attachEvent('on'+e,fn) : o.addEventListener(e,fn,false);
    },

    removeEvent:function(o,e,fn){
        return o.detachEvent ? o.detachEvent('on'+e,fn):o.removeEventListener(e,fn,false);
    },

    bind:function(o,fn){
        return function(){
            return fn.apply(o,arguments);
        }
    }
}
</script>