JS代码:文章来源:https://www.toymoban.com/news/detail-603320.html
<!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>Document</title>
<style>
*{margin: 0; padding: 0;}
#box1{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
top: 0px;
left: 0px;
}
</style>
</head>
<body>
<div id="box1">
</div>
<script>
window.onload = function() {
var box1 = document.querySelector('#box1')
// 鼠标按下
box1.onmousedown = (e) => {
// 获取鼠标相对于box元素的位置
e = e || window.event
var divX = e.offsetX
var divY = e.offsetY
// 鼠标移动,将鼠标位置给到box1
document.onmousemove = (e) => {
e = e || window.event
var x = e.clientX - divX >= 0 ? (e.clientX - divX) : 0
var y = e.clientY - divY >= 0 ? (e.clientY - divY) : 0
box1.style.left = x + 'px'
box1.style.top = y + 'px'
}
}
// 鼠标松开
box1.onmouseup = () => {
document.onmousemove = null
}
}
</script>
</body>
</html>
Vue代码:文章来源地址https://www.toymoban.com/news/detail-603320.html
<template>
<div class="legend">
<div class="mouse-drop" style="width: 120px;height: 120px;background: #f78"></div>
</div>
</template>
<script>
export default {
mounted() {
this.mouseDrop()
},
methods: {
// 鼠标拖拽
mouseDrop() {
let dom = document.querySelector('.legend')
let button = dom.querySelector('.mouse-drop')
// 鼠标按下
button.onmousedown = (e) => {
// 获取鼠标相对于box元素的位置
e = e || window.event
var divX = e.offsetX
var divY = e.offsetY
// 鼠标移动,将鼠标位置给到dom
document.onmousemove = (e) => {
e = e || window.event
var x = e.clientX - divX >= 0 ? (e.clientX - divX) : 0
var y = e.clientY - divY >= 0 ? (e.clientY - divY) : 0
dom.style.left = x + 2 + 'px'
dom.style.top = y + 42 + 'px'
}
}
// 鼠标松开
button.onmouseup = () => {
document.onmousemove = null
}
},
}
}
<script>
到了这里,关于JS、Vue鼠标拖拽的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!