关于完美拖拽的问题三
生活随笔
收集整理的這篇文章主要介紹了
关于完美拖拽的问题三
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
簡單的修改了一下,讓它自動吸附,原理很簡單,判斷t,l的距離,只要讓它在小于一個距離的時候距離變?yōu)? 就可以了
帶邊框的自動吸附的拖拽代碼如下:
<!doctype html> <html lang="en"><head><meta charset="UTF-8"><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0'/><title>帶框的吸附拖拽</title><style>*{margin:0;padding:0;}#div1{width:100px; height:100px; position:absolute; background:red;cursor:move;overflow:hidden;border-radius:8px;}.div2{border:1px dotted #333;position:absolute;border-radius:8px;}</style><script>window.onload=function(){var oDiv=document.getElementById("div1");var disX=disY=0;oDiv.onmousedown=function(event){var event=event || window.event;disX=event.clientX-oDiv.offsetLeft; //判斷鼠標(biāo)在div的X軸位置 disY=event.clientY-oDiv.offsetTop; //判斷鼠標(biāo)在div的y軸的位置var oBox=document.createElement("div");oBox.className="div2";oBox.style.width=(oDiv.offsetWidth-2)+"px";//為oBox的寬賦值 oBox.style.height=(oDiv.offsetHeight-2)+"px"; //為oBox 的高賦值 oBox.style.left=oDiv.offsetLeft+"px";//oBox的初始位置 oBox.style.top=oDiv.offsetTop+"px";document.body.appendChild(oBox);if(oDiv.setCapture){ //兼容ie的事件捕獲 oDiv.onmousemove=move;oDiv.onmouseup=up;oDiv.setCapture();}else{document.onmousemove=move; //兼容ff chrome document.onmouseup=up;}function move(event){var event=event||window.event;var l=event.clientX-disX;var t=event.clientY-disY;if(l<50){l=0;}else if(l>(document.documentElement.clientWidth-oBox.offsetWidth-50)){l=document.documentElement.clientWidth-oBox.offsetWidth;}if(t<50){t=0;}else if(t>(document.documentElement.clientHeight-oBox.offsetHeight-50)){t=document.documentElement.clientHeight-oBox.offsetHeight;}oBox.style.left=l+"px";oBox.style.top=t+"px";}function up(){oDiv.style.left=oBox.offsetLeft+'px';oDiv.style.top=oBox.offsetTop+'px';document.body.removeChild(oBox);this.onmousemove=null;this.onmouseup=null;if(oDiv.releaseCapture){oDiv.releaseCapture();}}return false;};}</script></head><body><div id="div1"></div></body> </html>?
轉(zhuǎn)載于:https://www.cnblogs.com/yuyu9988/p/3408569.html
總結(jié)
以上是生活随笔為你收集整理的关于完美拖拽的问题三的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 用css自定义滚动条样式
- 下一篇: 运用代码管理段来提升开发效率