title: 拖拽功能
tags: Vue
categories: JavaScript
abbrlink: 18a433ce
date: 2022-11-26 21:14:19
效果
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>监听鼠标行为</title>
<!-- Date: 2022-11-24 12:44:52 -->
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.10/dist/vue.js"></script>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body,
#app {
width: 100%;
height: 100%;
user-select: none;
}
#app {
background-color: bisque;
}
#x,
#y {
background-color: black;
position: absolute;
}
#x {
width: 100%;
height: 1px;
}
#y {
width: 1px;
height: 100%;
}
#GoldHB {
width: 100px;
background-color: gold;
position: absolute;
opacity: 50%;
text-align: center;
}
#GoldHB:hover {
cursor: move;
background-color: greenyellow;
border-radius: 70%;
}
</style>
</head>
<body>
<!-- 非input元素绑定键盘事件,需要加tabindex属性或者设置contenteditable属性为true, 需先点击元素后生效 -->
<div id="app" @mousemove="showPos" @mousedown="showButton" @mousewheel="scrolling">
<!-- 动态CSS -->
<div id="x" :style="{top: topSty}"></div>
<div id="y" :style="{left: x+'px'}"></div>
<h1> 鼠标当前坐标: ({{position}}) </h1>
<h1>你刚点击了 {{mouseBut}} </h1>
<h1>你刚按下了 {{keyBut}} </h1>
<h1>窗口中可视区域大小: {{window.innerWidth}}, {{window.innerHeight}} </h1>
<h1>拖动"我"试试, 或者滑动滚轮</h1>
<!-- 拖拽功能 -->
<div @mousedown.left="draging" id="GoldHB" :style="sty_GoldHB"></div>
</div>
<script>
const vm = new Vue({
el: '#app',
data: {
x: 0,
y: 0,
butCode: "",
keyBut: "",
// 优势, 可以方便的在这里添加更多动态的css样式
sty_GoldHB: {
height: '100px',
top: '142px',
left: '40px',
},
window,
},
created() {
// 全局监听 键盘按下事件
document.onkeydown = this.keyButton;
},
methods: {
showPos(e) {
// 偏移一个像素, 使鼠标能点中其他元素
this.x = e.clientX - 1;
this.y = e.clientY - 1;
},
showButton(e) {
this.butCode = e.button;
},
keyButton(e) {
this.keyBut = e.key;
},
scrolling(e) {
let h = parseInt(this.sty_GoldHB.height);
let w = e.wheelDelta / 10;
if ((h += w) < 0) h = 0;
this.sty_GoldHB.height = h + 'px';
},
draging(e) {
// 获取目标元素
let divGold = e.target;
// 当鼠标按下,就获得鼠标在盒子内的坐标(x,y)
let x = e.pageX - divGold.offsetLeft;
let y = e.pageY - divGold.offsetTop;
// 重新设置盒子距离左上的距离=> 当前鼠标的位置 - 点击时, 鼠标在盒子中的坐标
let move = () => {
// 这里的this指向Vue
this.sty_GoldHB.left = (this.x - x) + 'px';
this.sty_GoldHB.top = (this.y - y) + 'px';
}
// 添加鼠标移动事件
document.addEventListener('mousemove', move);
// 添加鼠标释放事件, 一旦释放鼠标, 移除鼠标移动事件, 即停止移动
document.addEventListener('mouseup', () => {
document.removeEventListener('mousemove', move)
})
},
},
computed: {
position() {
return this.x + ", " + this.y;
},
mouseBut() {
let arr = ["鼠标左键", "鼠标中键", "鼠标右键"];
return arr[this.butCode];
},
topSty() {
return this.y + 'px';
},
}
})
</script>
</body>
</html>