分享一篇旧笔记。温故而知新
主要思路:
1,鼠标点击拖拉框的时候确认鼠标距离整个被拉动窗口的左上角的位置。
2,鼠标移动时候确认被拖动的窗口距离可视窗口左上角的位置与1所求得的值的差
3,边界值判断
贴上代码
html:
<div class="a"> <div id="all" class="all"> <div class="top">鼠标点击区域</div> </div> </div
css:
<style type="text/css"> .all{ height: 300px; width: 450px; border:2px solid black; position: absolute; } .top{ height: 20%; width: 100%; background: pink; } .a{ height: 100%; width: 100%; border: 1px solid blue; } </style>
js:
<script> function getClassName(clsName,Parent){ var Parent = Parent?document.getElementById(Parent):document, eles=[], elements = Parent.getElementsByTagName("*"); for(var i=0;i<elements.length;i++){ if(clsName==elements[i].className){ eles.push(elements[i]); } } return eles; } window.onload = drag; function drag(){ //获取className=top的对象 var pannel=getClassName("top","all")[0]; //当鼠标点击时触发 alert(pannel.innerHTML); document.title="111"; pannel.onmousedown = fndrag; } function fndrag(event){ document.title="222"; var all = document.getElementById("all"); var pannel=getClassName("top","all")[0]; var event = event || window.event; //获取鼠标距离窗口的位置 var disX = event.clientX-all.offsetLeft; var disY = event.clientY-all.offsetTop; //鼠标移动 document.onmousemove=function(event){ var e = event || window.event; pannel.style.cursor="move"; fnmove(e,disX,disY); } //放开鼠标 document.onmouseup=function(){ document.onmouseup=null; document.onmousemove=null; pannel.style.cursor="auto"; } } function fnmove(e,disX,disY){ //获取窗口的位置(左上角) var l = e.clientX - disX; var t= e.clientY - disY; var all = document.getElementById("all"); //获取可视窗口的长宽,兼容浏览器 var winWid = document.documentElement.clientWidth || document.body.clientWidth; var winHei = document.documentElement.clientHeight || document.body.clientHeight; //获取窗口的最大宽度和长度(左上角) var maxWid = winWid-all.offsetWidth-10; var maxHei = winHei - all.offsetHeight-10; //超出左边间距 if(l<0){ l=10; } //超出右边间距 else if(l>maxWid){ l=maxWid; } //超出上面距离 if(t<0){ t=10; } else if(t>maxHei){ t=maxHei; } document.title = l+","+t; all.style.left = l+"px"; all.style.top= t+"px"; } </script>
效果展示:
PS:效果有一点奇葩,窗口会跑到顶部
鼠标点击区域
以上内容,如有错误请指出,不甚感激。