做了一个拖曳效果的例子
就是点住指定的子元素区域 父元素随着鼠标移动也跟随移动,类似QQ登录窗口点着上面一部分可以随便拉到页面任何一个地方
但是我做出来基础效果也有 但有一个问题就是我拖过一次放开鼠标后,再次点击鼠标,一移动,元素就回到最开始的位置了,求好心人帮我看一下哪里出问题了 。
以下是代码;
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>拖拽效果</title> <style> body{ position: relative; } #box{ width: 300px; height: 300px; background: #666; position: absolute; } #qq{ width: 100px; height: 100px; position: absolute; background:red; left: 100px; } </style> </head> <body> <div id="box"> <div id="qq"></div> </div> </body> </html>
这里是JS
<script src="base库.js"></script> <script> //事件添加函数; function addEvent(element,type,callback){ if(element.addEventListener){ element.addEventListener(type,callback,false); }else if(element.attachEvent){ element.attachEvent('on' + type,callback) } } addEvent(window,"load",drag); function drag() { var oBox = document.getElementById("box"); var oQQ = document.getElementById("qq"); addEvent(oQQ, "mousedown", fnDown); function fnDown(evt) { var e = evt || window.event; //鼠标摁下时光标和面板之间的距离 var disX = e.clientX, disY = e.clientY; //移动 document.onmousemove = function (evt) { var e = evt || window.event; fnMove(evt, disX, disY); }; //光标放开 document.onmouseup = function () { document.onmousemove = null; document.onmouseup = null; }; } function fnMove(evt, poxX, poxY) { var e = evt || window.event, l = e.clientX - poxX, t = e.clientY - poxY, winW = document.documentElement.clientWidth || document.body.clientWidth, winH = document.documentElement.clientHeight || document.body.clientHeight, maxW = winW - oBox.offsetWidth, maxH = winH - oBox.offsetHeight; if (l < 0) { l = 0 } else if (l > maxW) { l = maxW } if (t < 0) { t = 0 } else if (t > maxH) { t = maxH } oBox.style.left = l + "px"; oBox.style.top = t + "px"; } } </script>
相关分类