模仿《javascript權威指南》寫了個簡易拖拽程序,麻雀雖小五臟俱全。 原理:注冊mousemove事件,使元素跟隨鼠標挪動;注冊mouseup事件,移除mousemove事件,使得松開鼠標時元素不再跟隨移動,能夠固定在指定位置。在mousedown事件中注冊mousemove事件和mouseup事件,這樣便可完成一次完整的拖拽。 重點:IE中setCapture()的應用。它的作用是捕捉所有的MouseEvent,設置完成后,即使鼠標移出窗口注冊的鼠標事件仍然能夠被觸發(fā)。它在此處的作用是當鼠標移動過快越出元素的邊界使得原本將要失效的mousemove事件依然能夠發(fā)揮作用。在ff和chrome中,由于沒有對應的設置,可以把mousemove和mouseup事件指定到docuemnt對象上,這樣不管鼠標怎么移動,都在document上;其實在ie上這么寫也行,那就不用設置setCapture()了,它和設置了的相比唯一的區(qū)別是當元素向右移出窗口邊界時,元素始終保持在可視范圍內。
<!docType html> <html> <head> <style type="text/css"> #drag {border:1px solid blue;width:100px;height:100px;position:absolute;} </style> </head> <body> <input id="x" /> <input id="y" /> <div id="drag"></div> <script><!-- var drag = document.getElementById('drag'); var inputX = document.getElementById('x'); var inputY = document.getElementById('y'); if(document.attachEvent){ drag.attachEvent('onmousedown',dragHandle); }else{ drag.addEventListener('mousedown', dragHandle,false); } function dragHandle(event){ var event = event||window.event; var startX = drag.offsetLeft; var startY = drag.offsetTop; var mouseX = event.clientX; var mouseY = event.clientY; var deltaX = mouseX - startX; var deltaY = mouseY - startY; if(document.attachEvent){ drag.attachEvent('onmousemove',moveHandle); drag.attachEvent('onmouseup',upHandle); drag.attachEvent('onlosecapture',upHandle); drag.setCapture(); }else{ document.addEventListener('mousemove',moveHandle,true); document.addEventListener('mouseup',upHandle,true); } function moveHandle(event){ var event = event||window.event; drag.style.left = (event.clientX - deltaX)+"px"; drag.style.top = (event.clientY - deltaY)+"px"; inputX.value=drag.style.left; inputY.value=drag.style.top; } function upHandle(){ if(document.attachEvent){ drag.detachEvent('onmousemove',moveHandle); drag.detachEvent('onmouseup',upHandle); drag.detachEvent('onlosecapture',upHandle); drag.releaseCapture(); }else{ document.removeEventListener('mousemove',moveHandle,true); document.removeEventListener('mouseup',upHandle,true); } } } //--</script> </body> </html>
當然此例還可以擴展,比如限定拖拽范圍不允許移動到可視范圍外等,只要修改mousemove方法即可。