关于js在一个固定的盒子里面拖拽的问题(包含临界值)

  回武汉打卡第三天,武汉加油,逆战必胜!今天我们一起分享一下js拖拽的问题。

  当然实现拖拽方法是有很多的,下面简单讲一种方法,大致思路如下:

  首先需要用到的事件主要有  onmousedown,onmousemove,onmouseup。因为是小盒子(small)在拖拽拖拽,所以首先onmousedown是绑定在small小盒子上面;而拖拽是在文档中进行的,所以onmousemove和onmouseup可以写在文档对象上;

  其次css在书写时记得使用定位,不要使用fixed(位置是相对于浏览器窗口的)

  再次在鼠标按下的时候,计算鼠标在小盒子中的位置(鼠标的坐标 - 小盒子在文档中的坐标 - 大盒子的坐标)

  然后在鼠标移动的过程中,计算小盒子距离左边的距离,也就是定位值(鼠标的坐标 - 鼠标在小盒子中的位置)

  最后:判断临界值

    最小临界值都是0

    最大临界值:大盒子(big)的宽高 - 小盒子(small)的宽高

  值得注意的是获取鼠标坐标有两种办法,一种是clientX,clientY;另外一种是pageX,pageY;在这里前者会有一定问题(比如闪烁),建议使用pageX,pageY

  具体实现附代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
*{margin: 0;}
.big{ 600px;height: 500px;background-color: #000;margin: 50px auto;position: relative;border:30px solid red;}
.small{ 100px;height: 100px;background-color: #ff0;position: absolute;}
</style>
</head>
<body>
<div class="big">
<div class="small"></div>
</div>
<script type="text/javascript">
window.onload = function(){
// 获取元素
var bigBox = document.querySelector(".big");
var sBox = document.querySelector(".small");
// 获取大盒子的大小
var bigbox_w = bigBox.offsetWidth;
var bigbox_h = bigBox.offsetHeight;
// 获取小盒子的大小
var sbox_w = sBox.offsetWidth;
var sbox_h = sBox.offsetHeight;
// 获取大盒子的间距
var bigBox_l = bigBox.offsetLeft;
var bigBox_t = bigBox.offsetTop;
// 小盒子鼠标按下才触发事件
sBox.onmousedown = function(ev){
ev = ev || window.event;
// 获取鼠标在盒子中的位置
var disX = ev.pageX - sBox.offsetLeft;
var disY = ev.pageY - sBox.offsetTop;
console.log(disX,disY)
// 鼠标在文档中移动
document.onmousemove = function(e){
e = e || window.event;
var moveX = e.pageX - disX;
var moveY = e.pageY - disY;
if(moveX < 0){
moveX = 0;
}
if(moveY < 0){
moveY = 0;
}
if(moveX > bigbox_w - sbox_w){
moveX = bigbox_w - sbox_w;
}
if(moveY > bigbox_h - sbox_h){
moveY = bigbox_h - sbox_h;
}
sBox.style.left = moveX + 'px';
sBox.style.top = moveY + 'px';
}
}
document.onmouseup = function(){
document.onmousemove = null;
}
}
</script>
</body>
</html>

原文地址:https://www.cnblogs.com/chysunny/p/12620111.html