拖拽
① dom.onmousedown
② document.onmousemove
③ document.onmouseup
拖拽模型:
1、添加鼠标按下事件, 获取鼠标的定位值, 获取元素的定位值。
2、添加鼠标移动事件, 获取鼠标移动的定位值, 用移动后的距离 - 移动之前的距离 + 元素的定位值 就是当前元素移动值
3、鼠标抬起还要取消鼠标的移动事件。
1. 实现在视口随意拖拽
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#box {
width: 100px;
height: 100px;
background-color: red;
/*因为要运动, 所以要定位*/
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<div id="box"></div>
<script type="text/javascript">
// 获取元素
var box = document.getElementById("box");
// 添加鼠标点击事件
box.onmousedown = function(e) {
// 获取鼠标按下时候视口的位置
var x = e.clientX;
var y = e.clientY;
// 获取box的定位值
var left = parseInt(getComputedStyle(box)["left"]);
var top = parseInt(getComputedStyle(box)["top"]);
// 既然要移动,所以添加mousemove事件
document.onmousemove = function(e) {
// 获取移动后的鼠标位置
var m_x = e.clientX;
var m_y = e.clientY;
// 改变box的定位值
box.style.left = m_x - x + left + "px";
box.style.top = m_y - y + top + "px"
}
}
document.onmouseup = function() {
document.onmousemove = null;
}
</script>
</body>
</html>
2. 在一个规定宽高有范围的区域实现随意拖拽
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#box {
width: 800px;
height: 400px;
margin: 0 auto;
border: 1px solid blue;
position: relative;
}
#box1 {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<div id="box">
<div id="box1"></div>
</div>
<script type="text/javascript">
// 获取元素
var box1 = document.getElementById("box1");
var box = document.getElementById("box");
// 获取box的宽高值
var box_style = getComputedStyle(box);
// 获取box的高
var box_height = parseInt(box_style["height"]);
// 获取box的宽
var box_width = parseInt(box_style["width"]);
// 获取box1的宽高值
var box1_style = getComputedStyle(box1);
// 获取box的高
var box1_height = parseInt(box1_style["height"]);
// 获取box的宽
var box1_width = parseInt(box1_style["width"]);
// 添加鼠标点击事件
box1.onmousedown = function(e) {
// 获取鼠标的当前位置
var x = e.clientX;
var y = e.clientY;
// 获取box1的定位值
var left = parseInt(getComputedStyle(box1)["left"]);
var top = parseInt(getComputedStyle(box1)["top"]);
// 添加鼠标移动事件
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;
// 判定是否到达边界
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";
}
}
// 取消鼠标移动事件
document.onmouseup = function() {
document.onmousemove = null;
}
</script>
</body>
</html>