1. 程式人生 > >元素拖動

元素拖動

阻止 func pre 速度 p值 wid move eat splay

元素拖動涉及事件:mousedown,mousemove,mouseup
思路:鼠標按下點M1和移動後鼠標點M2的距離與元素開始時的left和移動後的left之間的距離是相同的:
1)鼠標按下時,計算鼠標坐標與元素left/top之間的距離disX/disY;
2)鼠標移動時,使用鼠標坐標減去disX和disY,就時元素的left和top值;
註意:
1)元素拖動速度過快時,鼠標脫離元素內,會導致拖動中斷或不連續:將move和up事件作用於document對象
2)img元素拖動時會有默認行為,會導致效果無法達到預期:在down事件的最後使用return false阻止掉默認行為
3)元素中間存在文本時,在ie瀏覽器上選中文本時會導致拖拽有問題:在down事件中使用setCapture全局捕獲(生成一個透明的層),在up事件中使用releaseCapture釋放全局捕獲(setCapture該法是IE瀏覽器專有)

<body>
  <div class="drag-box">我是足球標題</div>
  <img src="img/ball.jpg" class="drag-box"  style="display: none">
</body>
<style>
    .drag-box{position:absolute;width: 210px;height: 210px; background:url("img/ball.jpg") no-repeat;text-align: center}
</style>
window.onload = function
() { var dragBox = document.getElementsByClassName(‘drag-box‘)[0]; var disX = 0; var disY = 0; //鼠標按下drag-box dragBox.onmousedown = function (ev) { var ev = ev || window.event; disX = ev.clientX - dragBox.offsetLeft; disY = ev.clientY - dragBox.offsetTop;
//IE:全局捕獲 if(dragBox.setCapture){ dragBox.setCapture(); } //鼠標按下並拖動drag-box document.onmousemove = function (ev) { var L = ev.clientX - disX; var T = ev.clientY - disY; dragBox.style.left = L + ‘px‘; dragBox.style.top = T + ‘px‘; }; //鼠標松開,清除mouseMove和mouseUp事件 document.onmouseup = function (ev) { document.onmousemove = null; document.onmouseup = null; //IE:釋放全局捕獲 if(dragBox.releaseCapture){ dragBox.releaseCapture(); } }; //阻止img元素的默認行為 return false; }; }

元素拖動