拖拽流程: --1 当鼠标在被拖拽元素上按下时,开始拖拽 onmousedown --2 当鼠标移动时被拖拽元素跟随鼠标移动 onmousemove --3 当鼠标松开时,被拖拽元素固定在当前位置 onmouseup-->1 为一个叫box的div绑定一个鼠标按下事件(以下两个事件在此事件里发生,包裹)-->2 为document绑定一个onmousemove事件| a. 需获取鼠标的坐标(clientX和clientY)| b. 修改box的位置-->3 为document绑定一个鼠标松开事件 当鼠标松开时,把鼠标的移动事件设置为null document.onmousemove = null 松开事件也要取消 document.onmouseup = null
-->当我们拖拽一个网页中的内容时,浏览器会默认去搜索引擎中搜索内容,此时会导致拖拽功能的异常,这个是浏览器提供的默认行为,可以用'reture false'来取消,但是这个方法对IE8及以下浏览器不起作用
1 setCapture() 对相关的事件进行捕获 ,IE支持
-->当一个元素调用此方法时,这个元素将会把下一次所有的相关的事件捕获到自己的身上
2. releaseCapture() 取消对事件的捕获
<style> #box1 { width: 100px; height: 100px; background-color: pink; position: absolute; } </style> <p>我不想移动</p> <div id="box1"></div> <!-- <div id="box2"></div> --> <script src="./common.js"></script> <script> let box1 = document.getElementById('box1'); box1.onmousedown = function (event) { // 对鼠标按下相关的事件进行捕获(只对IE浏览器有效) box1.setCapture && box1.setCapture() event = event || window.event; // div的横坐标偏移量:鼠标.clentX - 元素.offsetLeft // div的纵坐标偏移量:鼠标.clentY - 元素.offsetTop let ol = event.clientX - box1.offsetLeft; let ot = event.clientY - box1.offsetTop; document.onmousemove = function (event) { event = event || window.event; let left = event.clientX - ol; let top = event.clientY -ot; // div的偏移量跟随鼠标移动 box1.style.left = left + 'px'; box1.style.top = top + 'px'; } document.onmouseup = function () { document.onmousemove = null document.onmouseup = null // 取消事件的捕获(只对IE浏览器有效) box1.releaseCapture && box1.releasePointerCapture() } // 当我们全选鼠标按下的点击事件时,浏览器会自动选中与起无关的标签,需取消默认行为 return false } </script>