0
点赞
收藏
分享

微信扫一扫

鼠标拖拽div效果的实现——节流阀思想


下面展示两种方法实现鼠标拖拽div的效果的完整代码

// 第一种方案:采用的是事件嵌套事件的方法

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
div {
width: 200px;
height: 200px;
background-color: #f99;
cursor: move;
/*坑:不要忘记定位,否则left、top设置不起效果*/
position: absolute;
left: 300px;
top: 100px;
}
</style>
<body>
<div id="box"></div>
<script>
//采用的是事件嵌套事件的方法
var box = document.querySelector("#box")
// 鼠标移上去没有触发事件,当鼠标点击的时候触发事件
box.onmousedown = function (e1) {
var x = e1.pageX - box.offsetLeft
var y = e1.pageY - box.offsetTop
// 当鼠标点击之后又触发移动事件(div跟随鼠标移动)
document.onmousemove = function (e2) {
box.style.left = e2.pageX - x + "px"
box.style.top = e2.pageY - y + "px"
}
}
// 当鼠标点击松开,移动事件解绑,不再移动
document.onmouseup = function () {
document.onmousemove = null
}
</script>
</body>
</html>

// 第二种方案:采用的是节流阀思想

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
div {
width: 200px;
height: 200px;
background-color: #f99;
cursor: move;
/*坑:不要忘记定位,否则left、top设置不起效果*/
position: absolute;
left: 300px;
top: 100px;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
// 节流阀思想精髓(使用套路)
// 1. 想清楚阀门来限制什么
// 2. 定义阀门,并且想清楚阀门一开始是开启的还是关闭的
// 3. 什么时候开启阀门,啥时候关闭阀门
var box = document.querySelector("#box");
var x, y;//局部变量可以访问全局变量,全局变量不可访问局部变量,局部变量不能访问局部变量。
var flag = false; // 阀门一开始是关闭的(一开始mousemove不能触发)
box.onmousedown = function (e1) {
// 鼠标摁下去事件触发阀门打开
// mousemove事件能触发,阀门开启了
flag = true;
x = e1.pageX - box.offsetLeft
y = e1.pageY - box.offsetTop
}

document.onmousemove = function (e2) {
if (flag) {
// flag === true,进入if ,flag为true,表示阀门是开启的
box.style.left = e2.pageX - x + "px"
box.style.top = e2.pageY - y + "px"
}
}
document.onmouseup = function() {
// 鼠标弹起来, mousemove事件不用了,把阀门再次关闭
flag = false;
}
</script>
</body>
</html>


举报

相关推荐

0 条评论