拖拽的原理
1.获取距离(鼠标的位置-odiv的外边距)
2.理解什么时候用onmousemove事件
3.判断是否过界
html代码:
<div id="div1"></div>
css代码:
#div1{width:100px;height:100px;background:red;position:absolute}javascript代码:
window.onload=function(){var oDiv=document.getElementById("div1");var x=0;var y=0;oDiv.onmousedown=function(ev){var oEvent=ev||event;//鼠标的横坐标减去div的offsetLeftx=oEvent.clientX-oDiv.offsetLeft;//鼠标的纵坐标减去div的offsetTopy=oEvent.clientY-oDiv.offsetTop;document.onmousemove=function(ev){var oEvent=ev||event; var left=oEvent.clientX-x;var right=oEvent.clientY-y;//判断左边是否过界if(left<0){left=0;}//判断右边是否过界else if(left>document.documentElement.clientWidth-oDiv.offsetWidth){left=document.documentElement.clientWidth-oDiv.offsetWidth;}//判断上边是否过界if(right<0){right=0;}//判断下边是否过界else if(right>document.documentElenment.clientHeight){right=document.documentElenment.clientHeight-oDiv.offsetHeight;}oDiv.style.left=left+"px";oDiv.style.top=right+"px";} document.onmouseup=function(){//清空document的事件document.onmousemove=null;document.onmouseup=null;}//解决低版本火狐bug,干掉系统默认return false;}}以上所述就是本文的全部内容了,希望大家能够喜欢。