八.拖拽

2017-08-15  本文已影响0人  2点半
<div id="div1"></div>
![](1.jpg)
#div1 {width: 100px; height: 100px; background: red; position: absolute;}
#img1 { position: absolute;}
var oDiv = document.getElementById('div1');
var oImg = document.getElementById('img1');
drag(oImg);
drag(oDiv);
function drag(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();
        }   
        document.onmousemove = function(ev) {
            var ev = ev || event;
            var L = ev.clientX - disX;
            var T = ev.clientY - disY;
            if ( L < 100 ) {
                L = 0;
            } else if ( L > document.documentElement.clientWidth - obj.offsetWidth ) {
                L = document.documentElement.clientWidth - obj.offsetWidth;
            }   
            if ( T < 0 ) {
                T = 0;
            } else if ( T > document.documentElement.clientHeight - obj.offsetHeight ) {
                T = document.documentElement.clientHeight - obj.offsetHeight;
            }
            obj.style.left = L + 'px';
            obj.style.top = T + 'px';
        }
        document.onmouseup = function() {
            document.onmousemove = document.onmouseup = null;
            if ( obj.releaseCapture ) {
                obj.releaseCapture();
            }
        }
        return false;   
    }
}
上一篇下一篇

猜你喜欢

热点阅读