拖拽
运用的是
鼠标事件 onmousedown() , onmousemove(),onmouseup()
计算鼠标距离视口左边 e.clientX
计算元素距离视口左边 box.offsetLeft
获取元素的宽度 box.clientWidth /box.offsetWidth
<head>
<style>
.box1{
height:400px;
width: 400px;
background: pink;
position: absolute;
top: 100px;
left: 100px;
}
.box2{
height:100px;
width: 100px;
background: palevioletred;
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="box1" id="box1">
<div class="box2" id="box2">
</div>
</div>
<script>
var box1 = document.querySelector(".box1");
var box2 = document.querySelector(".box2");
box2.onmousedown = function(e){
//鼠标按下时的位置
mouseX = e.clientX;
mouseY = e.clientY;
var left = box2.offsetLeft;
var top = box2.offsetTop;
document.onmousemove = function(e){
//鼠标移动时的位置
nowX = e.clientX;
nowY = e.clientY;
//被拖拽的盒子去到的位置等于盒子刚开始距离左边的位置 + 鼠标移动了的距离(终点-起点)
var resX = nowX - mouseX + left;
var resY = nowY - mouseY + top;
//盒子不被拽到大盒子外,所以要设定边界值
//拽到左边时,如果超过左边,box2.style.left = 0
if(resX < 0){
resX = 0
//拽到右边时 box2.style.left = box1.offsetWidth - box2.offsetWidth
}else if(resX > box1.offsetWidth - box2.offsetWidth){
resX = box1.offsetWidth - box2.offsetWidth;
}
if(resY < 0){
resY = 0
}else if(resY > box1.offsetHeight - box2.offsetHeight){
resY = box1.offsetHeight - box2.offsetHeight;
}
box2.style.left = resX +"px";
box2.style.top = resY +"px";
}
}
box2.onmouseup = function(){
document.onmousemove = null;
}
</script>
</body>