写一个兼容性比较好的拖拽DEMO
2015-07-29 21:57
399 查看
写一个兼容性比较好的拖拽DEMO
查看Demo思路
div盒子鼠标按下事件onmousedown
鼠标移动事件onmousemove,获得鼠标的坐标,将div移动至鼠标的当前坐标
鼠标抬起事件omouseup,清除鼠标移动事件和鼠标抬起事件
布局和代码
#div1 { background: rgb(40,40,40); width: 100px; height: 100px; position: absolute; color: #fff; }<body> 实例文字实例文字实例文字实例文字 <div id="div1">实例文字</div> 实例文字实例文字实例文字实例文字 <script> window.onload = function() { drag("div1"); } function drag(id) { var oDiv = document.getElementById(id); oDiv.onmousedown = function(ev) { var oEvent = event || ev; var disX = oEvent.clientX - oDiv.offsetLeft; var disY = oEvent.clientY - oDiv.offsetTop; oDiv.style.cursor = "move"; // for IE if (oDiv.setCapture) { oDiv.onmousemove = fnMove; oDiv.onmouseup = fnUp; oDiv.setCapture(); } else { document.onmousemove = fnMove; document.onmouseup = fnUp; } function fnMove(ev) { var oEvent = event || ev; var l = oEvent.clientX - disX; var t = oEvent.clientY - disY; // 磁性吸附 if (l < 50) { l = 0; } else if (l > document.documentElement.clientWidth - oDiv.offsetWidth-50) { l = document.documentElement.clientWidth - oDiv.offsetWidth; } if (t < 50) { t = 0; } else if (t > document.documentElement.clientHeight - oDiv.offsetHeight-50) { t = document.documentElement.clientHeight - oDiv.offsetHeight; } oDiv.style.left = l + 'px'; oDiv.style.top = t + 'px'; }; function fnUp() { this.onmousemove = null; this.onmouseup = null; if (this.releaseCapture) { this.releaseCapture(); } } return false; // 阻止文字选中 } } </script>
DEBUG
当页面中有其他元素的时候,鼠标拖拽时,会默认地去选中其他的诸如文字之类的东西,布局中的“实例文字”就是为此准备的。我们可以加入return false来解决掉很多浏览器默认事件,在这里就有一个很好的应用
微软的IE总是有自己的一套,这给js兼容带来了很大的麻烦,上述的bug解决方法在IE6下根本无效,因此这里引入了IE特有的
setCapture(),IE中,假设id为div1一个元素设置了setCapture(),然后再绑定事件,比如一个点击事件,接下来,无论你点击哪里,被触发的都是div1元素的点击事件了,甚至你点击浏览器的地址栏,工具栏,都会触发div1的点击事件()。此时你的ie浏览器会像中毒一样,点击关闭按钮都是在触发div1的点击事件(),其他元素不管在div之上还是之下的,他们绑定的点击事件全部失效。
这里刚好可以运用IE的
setCapture和
releaseCapture,当鼠标的div1上按下时,为div1 setCapture,这时所有的事件都集中到了div1身上,捕获所有事件,再也不会去选中其他的元素了,在鼠标抬起后,运用releaseCapture,不再捕获。