在限制范围内的拖拽
目录
在限制范围内的拖拽
css样式:
body{
margin: 0;
}
.box{
background: #eee;
width: 800px;
height: 400px;
border: 1px solid #ddd;
margin-left: 250px;
margin-top: 50px;
}
.box .smallbox{
width: 100px;
height: 100px;
position: absolute;
left: 20px;
top:20px;
background: red;
margin-left: 250px;
margin-top: 50px;
}
html的结构:
<div class="box">
<div class="smallbox"></div>
</div>
js代码:
var box = document.querySelector('.box');
var smallbox = document.querySelector('.box .smallbox');
smallbox.onmousedown = function(e){
e = e || event;
var divX = e.clientX - this.offsetLeft;
var divY = e.clientY - this.offsetTop;
document.onmousemove = function(e){
e = e|| event;
var l = e.clientX - divX - 250;
var t = e.clientY - divY - 50;
if(l<=0){
l = 0;
}else if(l>=box.clientWidth-smallbox.offsetWidth){
l = box.clientWidth-smallbox.offsetWidth;
}
if(t<=0){
t = 0;
}else if(t>=box.clientHeight-smallbox.offsetHeight){
t = box.clientHeight-smallbox.offsetHeight;
}
smallbox.style.cssText='left:'+l+'px;top:'+t+'px';
}
document.onmouseup = function(){
this.onmousemove=null;
}
return false;
}
转载自:https://blog.csdn.net/Stay_Hungry_Stay/article/details/81149679