<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>JavaScript拖拽樣本網頁——解決快速拖拽的問題</title> <meta name="Description" content="JavaScript拖拽文章的配套樣本網頁。本例解決了快速拖拽的時候元素停止移動的問題。" /> <meta name="Keywords" content="拖拽,執行個體,DOM,JavaScript,JScript" /> <style type="text/css"> .drag{border:1px solid; width:400px; background:#CCCCCC;} #test1{ top:20px;} #test2{ left:40px;} </style> <script type="text/javascript"> var dragElement = null; var mouseY; var mouseX; var x=""; var y=""; var max = 1; function dragInit(node){ if(node.className == "drag"){ node.onmousedown = down; document.onmousemove = move; node.onmouseover = over; node.style.position = "relative"; node.dragging = false; } var children = node.childNodes; for(var i = 0;i < children.length; i++){ dragInit(children[i]); } } window.onload = function(){ dragInit(document); document.onmouseup = docUp; } function down(event) { event = event || window.event; dragElement = this; mouseX = parseInt(event.clientX); mouseY = parseInt(event.clientY); objY = parseInt(getNodeStyle(dragElement,"top")); objX = parseInt(getNodeStyle(dragElement,"left")); //IE不返回未設定的CSS屬性 if(!objY)objY=0; if(!objX)objX=0; this.style.zIndex = max++; } function move(event){ event = event || window.event; if(dragElement){ var x,y; y = event.clientY - mouseY + objY; x = event.clientX - mouseX + objX; dragElement.style.top = y + "px"; dragElement.style.left = x + "px"; //移動完元素之後,延遲一段時間 document.onmousemove = null; setTimeout("document.onmousemove = move;",40); } } function docUp(){ dragElement = null; } function over(){ this.style.cursor = "move"; } function getNodeStyle(node,styleName){ var realStyle = null; if(node.currentStyle){ realStyle = node.currentStyle[styleName]; }else if(window.getComputedStyle){ realStyle = window.getComputedStyle(node,null)[styleName]; } return realStyle; } </script> </head> <body> <div class="drag" id="test1"> <p>我是拖拽樣本DIV1。</p> <p>可以實驗一下效果。</p> </div> <div class="drag" id="test2"> <p>我是拖拽樣本DIV2。</p> </div> </body> </html>
[Ctrl+A 全選 注:如需引入外部Js需重新整理才能執行]