<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;
this.originMouseY = event.clientY;
this.originContainX = this.position.right;
this.originContainY = this.position.top;
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;
}