The principle of drag and drop
1. Get the distance (mouse position - odiv margin)
2. Understand when to use onmousemove event
3. Determine whether it has crossed the boundary
html code:
<div id="div1"></div>
css code:
#div1{width:100px;height:100px;background:red;position:absolute}
javascript code:
window.onload=function(){ var oDiv=document.getElementById("div1"); var x=0; var y=0; oDiv.onmousedown=function(ev){ var oEvent=ev||event; //鼠标的横坐标减去div的offsetLeft x=oEvent.clientX-oDiv.offsetLeft; //鼠标的纵坐标减去div的offsetTop y=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; } }
The above is the entire content of this article, I hope you all like it.