<template>
<div class="drag-ball" :style="ballStyle" @mousedown="handleMouseDown"></div>
</template>
<script>
export default {
data() {
return {
isDragging: false,
ballPosition: { x: 0, y: 0 }, // 拖拽div初始位置
startPosition: { x: 0, y: 0 }, // 鼠标按下时的位置
};
},
computed: {
ballStyle() {
return {
position: "absolute",
right: `${this.ballPosition.x}px`,
bottom: `${this.ballPosition.y}px`,
};
},
},
methods: {
handleMouseDown(event) {
this.isDragging = true;
this.startPosition = { x: event.clientX, y: event.clientY };
document.addEventListener("mousemove", this.handleMouseMove);
document.addEventListener("mouseup", this.handleMouseUp);
},
handleMouseMove(event) {
if (this.isDragging) {
const diffX = event.clientX - this.startPosition.x;
const diffY = event.clientY - this.startPosition.y;
this.ballPosition = {
x: this.ballPosition.x - diffX,
y: this.ballPosition.y - diffY,
};
this.startPosition = { x: event.clientX, y: event.clientY };
this.constrainToScreen();
}
},
handleMouseUp() {
this.isDragging = false;
document.removeEventListener("mousemove", this.handleMouseMove);
document.removeEventListener("mouseup", this.handleMouseUp);
},
constrainToScreen() {
// 限制拖拽时在屏幕范围内
const windowWidth = window.innerWidth;
const windowHeight = window.innerHeight;
const ballRadius = 50; // 假设悬浮球半径为50px
if (this.ballPosition.x < ballRadius) {
this.ballPosition.x = ballRadius;
} else if (this.ballPosition.x > windowWidth - ballRadius) {
this.ballPosition.x = windowWidth - ballRadius;
}
if (this.ballPosition.y < ballRadius) {
this.ballPosition.y = ballRadius;
} else if (this.ballPosition.y > windowHeight - ballRadius - 100) {
this.ballPosition.y = windowHeight - ballRadius - 100;
}
},
},
};
</script>
<style lang="scss" scoped>
.drag-ball {
cursor: move;
background: #ffffff;
box-shadow: 0px 4px 30px 0px rgba(191, 212, 239, 1);
border-radius: 20px;
width: 50px;
height: 50px;
z-index: 999;
}
</style>
vue实现可拖拽图标,图标默认显示在右下角
于 2024-04-23 15:04:38 首次发布