1.HTML部分
<template>
<div
class="draggable-image"
:style="imageStyle"
@mousedown="startDrag"
@mousemove="doDrag"
@mouseup="endDrag"
@mouseleave="endDragNoClick"
>
<img :src="imageUrl" />
<!-- 遮罩元素 防止滑动过程中选中文字 影响拖拽 -->
<div v-show="dragging" class="drag-overlay"></div>
</div>
</template>
2.CSS部分
<style lang="scss" scoped>
.draggable-image {
cursor: pointer;
position: fixed;
width: 70px; /* 根据图片大小调整 */
height: 70px; /* 根据图片大小调整 */
display: flex;
justify-content: center;
align-items: center;
z-index: 999;
overflow: hidden; /* 防止拖拽时内容溢出 */
img {
width: 100%;
}
}
.drag-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0); /* 透明度可以根据需要调整 */
z-index: 998; /* 确保遮罩在拖拽元素之下 */
display: block;
}
</style>
3. JavaScript部分
<script>
export default {
data() {
return {
dragging: false,
posX: 0,
posY: 0,
offsetX: 0,
offsetY: 0,
screenWidth: 0,
screenHeight: 0,
imageUrl:'',
};
},
computed: {
imageStyle() {
return {
transform: `translate3d(${this.posX}px, ${this.posY}px, 0)`,
};
},
// 根据屏幕尺寸和元素大小计算位置限制
maxX() {
return this.screenWidth - this.$el.offsetWidth;
},
maxY() {
return this.screenHeight - this.$el.offsetHeight;
},
},
mounted() {
// 在组件挂载后获取屏幕尺寸
this.updateScreenSize();
// 监听窗口大小变化事件
window.addEventListener('resize', this.updateScreenSize);
},
beforeDestroy() {
// 组件销毁前移除事件监听器
window.removeEventListener('resize', this.updateScreenSize);
},
methods: {
updateScreenSize() {
this.screenWidth = window.innerWidth;
this.screenHeight = window.innerHeight;
this.posX = window.innerWidth - 80;
this.posY = window.innerHeight / 3.3;
},
startDrag(e) {
this.dragging = true;
this.offsetX = e.clientX - this.posX;
this.offsetY = e.clientY - this.posY;
this.$el.style.willChange = 'transform';
// 记录鼠标点击开始的坐标
this.startX = e.clientX;
this.startY = e.clientY;
},
doDrag(e) {
if (this.dragging) {
// 更新位置,同时确保不超出屏幕
this.posX = Math.min(Math.max(e.clientX - this.offsetX, 0), this.maxX);
this.posY = Math.min(Math.max(e.clientY - this.offsetY, 0), this.maxY);
requestAnimationFrame(() => {
this.$forceUpdate();
});
}
},
endDragNoClick() {
this.dragging = false;
this.$el.style.willChange = 'auto';
},
endDrag(e) {
this.dragging = false;
this.$el.style.willChange = 'auto';
if (Math.abs(this.startX - e.clientX) > 1 || Math.abs(this.startY - e.clientY) > 1) {
// 是拖拽操作,不触发点击事件
return;
}
this.handleClick();
},
handleClick() {
console.log('触发点击事件')
},
},
};
</script>