实现简单的鼠标拖拽事件


实现简单的鼠标拖拽事件

实现原理:在获取鼠标点击后,实现鼠标的移动事件,和鼠标按键松开事件。
首先获取当前div的左边和上边距离鼠标位置的距离,分别即为disXdisY。然后在鼠标后,实现鼠标移动的事件中,赋值给divstyle.leftstyle.top的值为当前鼠标的位置减去disXdisY后的值。

<style type="text/css">
*{
    margin: 0;
    padding: 0;
}
.box{
    position: absolute;
    width: 200px;
    height: 200px;
    background-color: red;
}
</style>
<div class="box" id="box"></div>
<script type="text/javascript">
var box = document.getElementById('box');
    document.onmousedown = function(ev){
        var oEvent = ev || window.event;
        disX = oEvent.clientX - box.offsetLeft;
        disY = oEvent.clientY - box.offsetTop;
        document.onmousemove = function(ev){
            var oEvent = ev || window.event;
            var l = oEvent.clientX - disX;
            var h = oEvent.clientY - disY;
            if(l < 0){
                l = 0;
            }else if(l > document.documentElement.clientWidth - box.offsetWidth){
                l = document.documentElement.clientWidth - box.offsetWidth;
            }
            if (h < 0) {
                h = 0;
            }else if(h > document.documentElement.clientHeight - box.offsetHeight){
                h = document.documentElement.clientHeight - box.offsetHeight;
            }
            box.style.left = l + 'px';
            box.style.top = h + 'px';
        }
        document.onmouseup =function(ev){
            var oEvent = ev || window.event;
            document.onmousemove = null;
            document.onmouseup = null;
        }
            return false;//禁止某些浏览器在div内容为空时,可能会出现的默认事件
    }
</script>

这里写图片描述

转载自:https://blog.csdn.net/u012832088/article/details/79805991

You may also like...