拖拽移动与点击事件同时存在
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="../../jquery.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
}
html,body {
height: 100%;
}
#canDrag {
position: relative;
width: 100px;
height: 100px;
background-color: aqua;
border: 1px solid #000;
}
</style>
</head>
<body>
<div id="canDrag"></div>
<script>
// 实现拖动和点击放大缩小
// 问题关键点:1.解决在拖动抬起后会触发点击的问题
// 2.在屏幕边界被遮挡显示不全
// 3.鼠标拖动太快,指针移出了块内,但还在拖动的情况
// 知识点: 触发顺序 onmousedown onmousemove onmouseup onclick
// onmousemove只要在块内移动就会触发,所以可以通过是否按下后触发移动(也可以在up后清除move事件)
// 解决方案: 1.onmousedown重置isMove,onmousemove中,设置为正在移动,在点击事件中判断是否存在移动,存在就不触发点击逻辑
// 2. 计算好最大的left和最大的top,做边界处理
// 3.mousemove事件绑定在document上 (body上不行,因为鼠标移出可视区后,抬起鼠标触发不到up事件)
//新的left就是:e.clientX 减去(e.clientX距离父盒子的距离 提前计算好)
let isMove = false
let isBig = false
$('#canDrag').mousedown(function(e){
isMove = false
console.log("鼠标按下了");
// 拖动盒子距离其父盒子的距离
this.disx = e.clientX - this.offsetLeft
this.disy = e.clientY - this.offsetTop
this.maxL = document.documentElement.clientWidth - this.offsetWidth
this.maxT = document.documentElement.clientHeight - this.offsetHeight
var that = this
$(document).mousemove(function(e){
move.call(that,e)
})
$(document).mouseup(function(e){
up.call(that,e)
})
})
function move (e) {
isMove = true
console.log("鼠标在移动");
//创建遮罩层.....
let _x = e.clientX - this.disx
let _y = e.clientY - this.disy
// 边界判断
if(_x >= this.maxL) {
_x = this.maxL
}
if(_x < 0) {
_x = 0
}
if(_y >= this.maxT) {
_y = this.maxT
}
if(_y < 0) {
_y = 0
}
this.style.left = _x + 'px'
this.style.top = _y + 'px'
}
function up (e) {
console.log("鼠标抬起了");
// 防止抬起后,移动鼠标--盒子一直跟着鼠标移动
$(document).off('mousemove')
$(document).off('mouseup')
//移除遮罩层.....
}
$('#canDrag').click( function (e) {
// 没有在移动,说明在点击
if (!isMove) {
if (isBig) {
isBig = false
console.log("鼠标点击了");
dom.style.transform = 'scale(1)'
} else {
isBig = true
console.log("鼠标点击了");
dom.style.transform = 'scale(2)'
}
}
})
</script>
</body>
</html>
一些情况:
在 iframe 上无法捕获 mousemove ,所以在move过程中创建遮罩层(不能在down中添加,因为会导致点击事件失效),up的时候移除遮罩层
如果拖动的是图片,要阻止默认事件
2万+




被折叠的 条评论
为什么被折叠?



