点滴积累【JS】---JS小功能(onmousedown实现鼠标拖拽div移动)
效果:
思路:
利用onmousedown事件实现拖拽。首先获得鼠标横坐标点和纵坐标点到div的距离,然后当鼠标移动后再用可视区的距离减去横纵坐标与div的距离。然后在判断不让DIV移出可视区,然后再赋予DIV的位置。最后关闭鼠标onmouseup事件。
代码:
1 <head runat="server"> 2 <title></title> 3 <style type="text/css"> 4 #div1 5 { 6 width: 200px; 7 height: 200px; 8 background: #00FFFF; 9 position: absolute; 10 border: 1px solid; 11 } 12 </style> 13 <script type="text/javascript"> 14 window.onload = function () { 15 var div = document.getElementById('div1'); 16 var disX = 0; 17 var disY = 0; 18 document.onmousedown = function (ev) { //鼠标按下 19 var oEvent = ev || event; //判断浏览器兼容 20 disX = oEvent.clientX - div1.offsetLeft; //鼠标横坐标点到div的offsetLeft距离 21 disY = oEvent.clientY - div1.offsetTop; //鼠标纵坐标点到div的offsetTop距离 22 document.onmousemove = function (ev) { //鼠标移动 23 var oEvent = ev || event; 24 var l = oEvent.clientX - disX; //获取div左边的距离 25 var t = oEvent.clientY - disY; //获取div上边的距离 26 if (l < 0) { //判断div的可视区,为避免DIV失去鼠标点 27 l = 0; 28 } 29 else if (l > document.documentElement.clientWidth - div.offsetWidth) { 30 l = document.documentElement.clientWidth - div.offsetWidth; 31 } 32 if (t < 0) { 33 t = 0; 34 } 35 else if (t > document.documentElement.clientHeight - div.offsetHeight) { 36 t = document.documentElement.clientHeight - div.offsetHeight; 37 } 38 div.style.left = l + 'px'; //确定DIV的左边位置 39 div.style.top = t + 'px'; //确定DIV的上边位置 40 } 41 document.onmouseup = function () { //当鼠标松开后关闭移动事件和自身事件 42 document.onmousemove = null; 43 document.onmouseup = null; 44 } 45 return false; 46 } 47 } 48 </script> 49 </head> 50 <body> 51 <div id="div1"> 52 </div> 53 </body>