美文网首页
mpvue小程序页面悬浮按钮可拖拽

mpvue小程序页面悬浮按钮可拖拽

作者: 泪滴在琴上 | 来源:发表于2023-09-12 17:48 被阅读0次
     <div class="floating-button"
                :style="{ position: 'fixed', right: buttonStyle.right, top: buttonStyle.top, transform: buttonStyle.transform }"
                @touchstart="startDrag" @touchmove="onDrag" @touchend="endDrag" @touchcancel="endDrag">
            </div>
    
     data() {
            return {
                buttonStyle: {
                    position: "fixed",
                    right: "20px",
                    top: "300px",
                    zIndex: 999,
                },
    }
    }
    
    methods: {
            startDrag(event) {
                event.preventDefault(); // 阻止默认行为
                this.dragging = true;
                console.log(event)
                // 记录初始触摸位置
                this.initialX = event.touches[0].clientX;
                this.initialY = event.touches[0].clientY;
    
                // 记录当前偏移量
                this.offsetX = parseInt(this.buttonStyle.right.slice(0, -2));
                this.offsetY = parseInt(this.buttonStyle.top.slice(0, -2));
            },
            onDrag(event) {
                event.preventDefault(); // 阻止默认行为
                if (this.dragging) {
                    // 计算偏移量
                    const deltaX = event.touches[0].clientX - this.initialX;
                    const deltaY = event.touches[0].clientY - this.initialY;
                    // 更新按钮位置
                    this.buttonStyle.right = `${this.offsetX - deltaX}px`;
                    this.buttonStyle.top = `${this.offsetY + deltaY}px`;
                }
            },
            endDrag() {
                this.dragging = false;
            },
    }
    
    .floating-button {
        width: 80rpx;
        height: 80rpx;
        background: green;
    }
    

    相关文章

      网友评论

          本文标题:mpvue小程序页面悬浮按钮可拖拽

          本文链接:https://www.haomeiwen.com/subject/xskuvdtx.html