<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<style>
.box {
position: absolute;
width: 200px;
height: 200px;
background: red;
transition: all .1s;
cursor: pointer;
}
.main{
width: 800px;
height: 900px;
background: pink;
}
</style>
</head>
<body>
<div class="main">
<div class="box"></div>
</div>
<script>
var box = document.getElementsByClassName("box")[0]; //获取元素
var x, y; //鼠标相对与div左边,上边的偏移
var isDrop = false; //移动状态的判断鼠标按下才能移动
box.onmousedown = function(e) {
var e = e || window.event; //要用event这个对象来获取鼠标的位置
x = e.clientX - box.offsetLeft;
y = e.clientY - box.offsetTop;
isDrop = true; //设为true表示可以移动
}
document.onmousemove = function(e) {
//是否为可移动状态
if(isDrop) {
var e = e || window.event;
var moveX = e.clientX - x; //得到距离左边移动距离
var moveY = e.clientY - y; //得到距离上边移动距离
//判断,如果移动的位置超过了外层div 减去 里面div的宽度,就说明到底了,给他设置死,800-200
if(moveX >=600){
moveX =600
}
if(moveY>=700){
moveY =700
}
//可移动最大距离
var maxX = document.documentElement.clientWidth - box.offsetWidth;
var maxY = document.documentElement.clientHeight - box.offsetHeight;
moveX=Math.min(maxX, Math.max(0,moveX));
moveY=Math.min(maxY, Math.max(0,moveY));
box.style.left = moveX + "px";
box.style.top = moveY + "px";
} else {
return;
}
}
document.onmouseup = function() {
isDrop = false; //设置为false不可移动
}
</script>
</body>
</html>
div在范围内拖拽
最新推荐文章于 2024-01-11 11:07:44 发布