关于移动div的具体实现(js)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>移动框练习</title> <style type = "text/css"> #big{width: 300px;height: 200px;position: absolute;top: 200px;left: 300px;background: #ccc;} h1{width: 200px;height: 50px;line-height: 50px;text-align: center;background: orange;margin: 0 auto; cursor: move;} </style> </head> <body> <div id="big"> <h1 class="titl"></h1> </div> <script type="text/javascript"> //通过父元素获取到指定想要获取的元素。 function getClass(clsName,parent){ var oParent = parent?document.getElementById(parent):document; var oH1 = oParent.getElementsByClassName(clsName)[0]; return oH1; } window.onload = drag; //给h1添加按住的事件。 function drag(){ var h1Node = getClass("titl","big"); h1Node.onmousedown = fnDown; } //通过函数来获取指针的位置。 function fnDown(event) { event = event || window.event; var oDiv = document.getElementById("big"), //光标按下时光标和面板之间的距离。 disX = event.clientX-oDiv.offsetLeft; disY = event.clientY-oDiv.offsetTop; document.onmousemove = function(event) { event = event || window.event; fnMove(event,disX,disY); } document.onmouseup = function(){ document.onmousemove = null; } } function fnMove(e,posX,posY) { var oDiv = document.getElementById("big"), l = e.clientX-posX, t = e.clientY-posY, winW = document.documentElement.clientWidth || document.body.clientWidth, winH = document.documentElement.clientHeight || document.body.clientHeight, maxW = winW-oDiv.offsetWidth, maxH = winH-oDiv.offsetHeight; if (l<0) { l=10; } else if(l>maxW){ l=maxW; } if (t<0) { t=10; } else if(t>maxH){ t=maxH; } oDiv.style.left = l+"px"; oDiv.style.top = t+"px"; } </script> </body> </html>