<!DOCTYPE html>
<html>
<head>
<title>拖拽元素</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
</head>
<body>
<div id="app">
<div
class="draggable"
@mousedown="handleMouseDown"
:style="{ top: top + 'px', left: left + 'px', backgroundColor: backgroundColor }"
>
<!-- 在这里放置您想要拖拽的内容 -->
</div>
</div>
<script>
new Vue({
el: '#app',
data: {
dragging: false, // 是否正在拖拽
mouseX: 0, // 鼠标在元素内的X坐标
mouseY: 0, // 鼠标在元素内的Y坐标
left: 0, // 元素左上角距离父容器左侧的距离
top: 0, // 元素左上角距离父容器顶部的距离
backgroundColor: 'lightblue', // 设置背景颜色,默认为'lightblue'
},
methods: {
handleMouseDown(event) {
this.dragging = true;
this.mouseX = event.clientX;
this.mouseY = event.clientY;
document.addEventListener('mousemove', this.handleMouseMove);
document.addEventListener('mouseup', this.handleMouseUp);
},
handleMouseMove(event) {
if (this.dragging) {
const deltaX = event.clientX - this.mouseX;
const deltaY = event.clientY - this.mouseY;
this.left += deltaX;
this.top += deltaY;
this.mouseX = event.clientX;
this.mouseY = event.clientY;
}
},
handleMouseUp(event) {
this.dragging = false;
document.removeEventListener('mousemove', this.handleMouseMove);
document.removeEventListener('mouseup', this.handleMouseUp);
},
},
});
</script>
<style>
.draggable {
position: absolute;
width: 100px;
height: 100px;
background-color: lightblue; /* 设置默认背景颜色 */
cursor: move;
user-select: none;
}
</style>
</body>
</html>
基于vue实现自由拖拽
最新推荐文章于 2024-04-29 23:04:47 发布