vue实现全屏拖拽

28 阅读1分钟
<!-- html-->
<div
    :style="containerStyle"
>
   <button>拖拽按钮</button>
</div>
data() {
    return {
        width: 88,
        height: 88,
        position: {
            top: document.body.offsetHeight / 2,
            right: 20
        },
        zIndex: 991,
        bodyWidth: document.body.offsetWidth,
        bodyHeight: document.body.offsetHeight,
    }
},

computed() {
    containerStyle() {
        return {
            top: `${this.position.top}px`,
            right: `${this.position.right}px`,
            width: `${this.width}px`,
            height: `${this.height}px`,
            zIndex: this.zIndex
        };
    }
},

methods: {
    startDrag(event) {
        this.originMouseX = event.clientX; // 鼠标初始 X 坐标
        this.originMouseY = event.clientY; // 鼠标初始 Y 坐标
        this.originContainX = this.position.right; // 元素初始 X 坐标
        this.originContainY = this.position.top; // 元素初始 Y 坐标
        document.addEventListener('mousemove', this.handleDrag);
        document.addEventListener('mouseup', this.stopDrag);
    },
    
    // 拖拽过程: 容器当前位置 = 鼠标当前位置 - 鼠标初始位置 + 容器初始位置;
    handleDrag(event) {
        event.preventDefault();
        event.stopPropagation();
        const x = this.originMouseX - event.clientX + this.originContainX;
        const y = event.clientY - this.originMouseY + this.originContainY;
        this.position.right = x < 0 ? 0 : (x > this.bodyWidth - this.width ? this.bodyWidth - this.width : x);
        this.position.top = y < 0 ? 0 : (y > this.bodyHeight - this.height ? this.bodyHeight - this.height : y);
    },
    
    // 停止拖拽
    stopDrag() {
        document.removeEventListener('mousemove', this.handleDrag);
        document.removeEventListener('mouseup', this.stopDrag);
    },
}
.toggle-button-box {
    position: fixed;
    cursor: grab;
}