JS、Vue鼠标拖拽

JS代码:

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代码:

javascript 复制代码
<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>
相关推荐
@yanyu66610 小时前
登录注册功能-明文
vue.js·springboot
cn_mengbei13 小时前
用React Native开发OpenHarmony应用:Reanimated共享元素过渡
javascript·react native·react.js
kyriewen13 小时前
前端测试:别为了100%覆盖率而写测试,那是自欺欺人
前端·javascript·单元测试
Data_Journal13 小时前
如何使用cURL更改User Agent
大数据·服务器·前端·javascript·数据库
掌心向暖RPA自动化13 小时前
如何获取网页某个元素在屏幕可见部分的中心坐标影刀RPA懒加载坐标定位技巧
java·javascript·自动化·rpa·影刀rpa
竹林81814 小时前
wagmi v2 多链钱包切换:一个 Uniswap 仿盘项目让我踩了三天坑
前端·javascript
你也向往长安城吗14 小时前
最快的 JavaScript navmesh pathfinding3d 算法。
javascript
滕青山14 小时前
在线PDF拆分工具核心JS实现
前端·javascript·vue.js
兔子零102416 小时前
Ofox AI值得用吗?
前端·javascript·后端
We་ct16 小时前
React 性能优化精讲
前端·javascript·react.js·性能优化·前端框架·html·浏览器