js拖动的问题
截图:
HTML:
<div class="bg" id="img">
<!-- 可拖到物体 -->
<div
class="common"
@touchstart.capture.stop="down"
@touchmove.capture.stop="move($event)"
@touchend.capture.stop="end">
<div class="son"></div>
</div>
<!-- 背景图 -->
<img src="@/assets/images/banner.jpg" width="100%">
</div>
变量:
return {
//拖动
flags: false,
nx: '',
ny: '',
dx: '',
dy: '',
xPum: '',
yPum: '',
position: {
x: 0,
y: 0 ,
},
}
方法:
//手指按下
down:function(e){
let moveDiv = e.target;
this.flags = true;
this.position.x = e.touches[0].clientX;
this.position.y = e.touches[0].clientY;
this.dx = moveDiv.offsetLeft; //0,相当于css的left
this.dy = moveDiv.offsetTop; //0,相对于css的top
},
//拖动
move:function(e){
let odiv = e.target;
let oArea = document.getElementById('img'); //父级DOM,用来限定拖动区域
this.nx = e.touches[0].clientX - this.position.x;
this.ny = e.touches[0].clientY - this.position.y;
this.xPum = this.dx + this.nx;
this.yPum = this.dy + this.ny;
//限制拖动区域
let maxRight = oArea.clientWidth - odiv.clientWidth; //父级宽度 - 本身宽度
let maxTop = oArea.clientHeight - odiv.clientHeight; //父级高度 - 本身高度
let resultX =0;
let resultY = 0;
//如果left为0
if(this.xPum <= 0){
this.xPum = 0;
}
//如果right为0
if(this.xPum > maxRight){
this.xPum = maxRight;
}
//如果top为0
if(this.yPum < 0){
this.yPum = 0;
}
//如果bottom为0
if(this.yPum >= maxTop){
this.yPum = maxTop;
}
//移动
odiv.style.left = this.xPum + "px";
odiv.style.top = this.yPum + "px";
},
//手指松开
end:function(){
this.flags = false;
},
问题:
按着父级(粉色),可以拖动
按着子级(黑色),不可以拖动
怎样才能解决此问题呢?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可以判断e.target是否是等于父级, 如果不是则return
判断下e.target,如果是父级元素就继续,不是就return;