JS 拖拽

实现后效果

实现原理:

  1. 在允许拖拽的节点元素上,监听mousedown(按下鼠标按钮)事件,鼠标按下后,事件触发
  2. 监听mousemove(鼠标移动)事件,修改克隆出来的节点的坐标,实现节点跟随鼠标的效果
  3. 监听mouseup(放开鼠标按钮)事件,将原节点克隆到鼠标放下位置的容器里,将绑定的mousemove和mouseup事件清除掉,拖拽完成。

拖拽方法实现

//鼠标拖拽方法
function drag(e) {

    var event = e || window.event;  //事件兼容
    var disX = event.clientX - this.offsetLeft, //当前鼠标在区块上的横向相对位置
        disY = event.clientY - this.offsetTop;  //当前鼠标在区块上的纵向相对位置
    var that = this;
    //鼠标移动
    document.onmousemove = function (e) {

        var newLeft = e.clientX - disX,
            newTop = e.clientY - disY;
        that.style.left = newLeft + 'px';
        that.style.top = newTop + 'px';
    }
    //鼠标键弹起
    document.onmouseup = function () {
        document.onmousemove = null;
        document.onmouseup = null;
    }
}

HTML部分

<!DOCTYPE html>
<html>
<head>
	<title>模拟重力场运动(碰撞检测&拖拽)</title>
    <style>
    div{
        position: absolute;
        left: 0;
        top: 0;
        width: 100px;
        height: 100px;
        background-color: orange;
        border-radius: 50%;
        cursor: pointer;
    }
    </style>
</head>
<body>
    <div></div>

<script type="text/javascript">

var oDiv = document.getElementsByTagName('div')[0];
oDiv.onmousedown = drag;    //拖拽事件绑定

</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_37746973/article/details/80748879