标签:abs text round .com oct alt meta 原理 absolute
1 <!DOCTYPE html> 2 <html> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title>鼠标拖拽定位元素</title> 7 <style> 8 #box { 9 width: 100px; 10 height: 100px; 11 background-color: aquamarine; 12 position: absolute; 13 } 14 </style> 15 </head> 16 17 <body> 18 <div id="box"></div> 19 <script type="text/javascript"> 20 var oDiv = document.getElementById("box"); 21 oDiv.onmousedown = function(ev) { 22 var oEvent = ev; 23 var disX = oEvent.clientX - oDiv.offsetLeft; 24 var disY = oEvent.clientY - oDiv.offsetTop; 25 document.onmousemove = function(ev) { 26 oEvent = ev; 27 oDiv.style.left = oEvent.clientX - disX + "px"; 28 oDiv.style.top = oEvent.clientY - disY + "px"; 29 } 30 document.onmouseup = function() { 31 document.onmousemove = null; 32 document.onmouseup = null; 33 } 34 } 35 </script> 36 </body> 37 38 </html>
原理:根据 absolute 定位结合鼠标事件实现对元素的拖动定位。
DOM元素各种尺寸和窗口的各种尺寸详解:详见下图
标签:abs text round .com oct alt meta 原理 absolute
原文地址:https://www.cnblogs.com/sunyuweb/p/8966598.html