js拖动的问题

发布于 2022-09-11 19:59:33 字数 2199 浏览 19 评论 0

截图:

clipboard.png

clipboard.png

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技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

空宴 2022-09-18 19:59:33

可以判断e.target是否是等于父级, 如果不是则return

以往的大感动 2022-09-18 19:59:33

判断下e.target,如果是父级元素就继续,不是就return;

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文