javascript——拖拽函數封裝

CSS部分:函數

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

HTML部分:this

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

JS部分:spa

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;
            };
        };
    };
相關文章
相關標籤/搜索