javascript——拖拽函数封装

CSS部分:

#div1{ width: 100px; height: 100px; background: #ccc; position: absolute;}
#img1{ position: absolute;}

HTML部分:

<div id="div1"></div>
<img id="img1" src="img/1.jpg" />

JS部分:

window.onload = function(){
        //获取相关元素
        var oDiv = document.getElementById('div1');
        var oImg = document.getElementById('img1');

        //函数调用
        drag(oDiv);
        drag(oImg);

        //函数封装
        function drag(obj){
            //obj鼠标按下
            obj.onmousedown = function(ev){

                var ev = ev || event;

                var disX = ev.clientX - this.offsetLeft;
                var disY = ev.clientY - this.offsetTop;

                if(obj.setCapture){
                    obj.setCapture();
                }
                
                //obj鼠标移动
                document.onmousemove = function(ev){

                    var ev = ev || event;

                    obj.style.left = ev.clientX - disX + 'px';
                    obj.style.top = ev.clientY - disY + 'px';
                };

                //obj鼠标释放
                document.onmouseup = function(){
                    document.onmousemove = document.onmouseup = null;
                    if(obj.releaseCapture){
                        obj.releaseCapture();
                    }
                }
                return false;
            };
        };
    };

 

posted @ 2015-03-30 17:27  波克比520  阅读(160)  评论(0编辑  收藏  举报