拖拽行为

拖拽div的代码

var box = document.querySelector(".box");
box.onmousedown = function(e){
    // 鼠标按下就应该获取到光标在div上的位置
    // var e = e || window.event;
    // var x = e.offsetX;
    // var y = e.offsetY;
    document.onmousemove = function(ev){
        // 光标移动过程中 - 让div移动
        var ev = ev || window.event;
        // 获取光标在浏览器的位置
        var x1 = ev.clientX;
        var y1 = ev.clientY;
        // left = x1 - x
        // var l = x1 - x;
        // var t = y1 - y;
        var l = x1 - box.offsetWidth/2;
        var t = y1 - box.offsetHeight/2;
        if(l<=0){
            l=0
        }
        if(t<=0){
            t = 0
        }

        if(l>=document.documentElement.clientWidth - box.offsetWidth){
            l = document.documentElement.clientWidth - box.offsetWidth
        }
        if(t>=document.documentElement.clientHeight - box.offsetHeight){
            t = document.documentElement.clientHeight - box.offsetHeight
        }
        // console.log(x,y);
        box.style.left = l + "px"
        box.style.top = t + "px"
    }
}
// 松开鼠标,解绑move事件
window.onmouseup = function(){
    document.onmousemove = null
}

 

posted @ 2021-01-12 15:31  技术活当赏  阅读(82)  评论(0)    收藏  举报