JS代码:
<!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.eventvar divX = e.offsetXvar divY = e.offsetY// 鼠标移动,将鼠标位置给到box1document.onmousemove = (e) => {e = e || window.eventvar x = e.clientX - divX >= 0 ? (e.clientX - divX) : 0var y = e.clientY - divY >= 0 ? (e.clientY - divY) : 0box1.style.left = x + 'px'box1.style.top = y + 'px'}}// 鼠标松开box1.onmouseup = () => {document.onmousemove = null}}</script>
</body>
</html>
Vue代码:
<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.eventvar divX = e.offsetXvar divY = e.offsetY// 鼠标移动,将鼠标位置给到domdocument.onmousemove = (e) => {e = e || window.eventvar x = e.clientX - divX >= 0 ? (e.clientX - divX) : 0var y = e.clientY - divY >= 0 ? (e.clientY - divY) : 0dom.style.left = x + 2 + 'px'dom.style.top = y + 42 + 'px'}}// 鼠标松开button.onmouseup = () => {document.onmousemove = null}},}
}
<script>