十三、限制拖拽模型

十三、限制拖拽模型

1
2
3
<div id="box">
<div id="box1"></div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#box {
width: 800px;
height: 400px;
border: 1px solid red;
position: relative;
margin: 0 auto;
}
#box1 {
width: 100px;
height: 100px;
left: 0;
top: 0;
background-color: red;
position: absolute;
}

执行代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// 获取元素
var box = document.getElementById("box");
var box1 = document.getElementById("box1");

// 获取box和box1的宽度和高度
var box_style = getComputedStyle(box);
var box_width = parseInt(box_style["width"]);
var box_height = parseInt(box_style["height"]);
// console.log("box:", box_width, box_height);

var box1_style = getComputedStyle(box1);
var box1_width = parseInt(box1_style["width"]);
var box1_height = parseInt(box1_style["height"]);
// console.log("box1:", box1_width, box1_height);

// 给box1添加mousedown事件
box1.onmousedown = function(e){
// 获取鼠标位于视口的位置
var x = e.clientX;
var y = e.clientY;

// 获取元素定位值
var left = parseInt(getComputedStyle(box1)["left"]);
var top = parseInt(getComputedStyle(box1)["top"]);

// 给document添加mousemove事件
document.onmousemove = function(e){
// 获取鼠标移动后的位置
var m_x = e.clientX;
var m_y = e.clientY;

// 定义变量 用于简化代码
var resultX = m_x - x + left;
var resultY = m_y - y + top;
// console.log(resultX, resultY);

// 进行边界限制
if (resultX < 0){
resultX = 0;
} else if (resultX > box_width - box1_width){
resultX = box_width - box1_width;
}
if (resultY < 0){
resultY = 0;
} else if (resultY > box_height - box1_height){
resultY = box_height - box1_height;
}

// 赋值box1的定位值
box1.style.left = resultX + "px";
box1.style.top = resultY + "px";
// console.log(resultX, resultY);
}
}

// 鼠标离开 清除mousemove事件
document.onmouseup = function(){
document.onmousemove = null;
}

输出结果:

UMuOhQ.png

点击查看

本文标题:十三、限制拖拽模型

文章作者:Mango

发布时间:2020年07月13日 - 22:33:55

最后更新:2020年07月14日 - 13:27:10

原始链接:https://mango185.github.io/post/77eec3d5.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

-------------------本文结束 感谢您的阅读-------------------