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>
相关推荐
meilindehuzi_a4 小时前
从零理解并实现 RAG:用 LangChain.js 构建语义检索问答系统
开发语言·javascript·langchain
鱼樱前端5 小时前
别再自己拼凑了!这款 Vue 3.5+ 严肃产品级组件库,把 AI 对话、工作流和复杂数据全包了!
javascript·vue.js·github
Listen·Rain6 小时前
Vue3:setup详解
前端·javascript·vue.js
kyriewen7 小时前
面试官让我优化一个卡死的表格,我打开 Claude 五秒重写,他放下咖啡问我要不要来当组长
前端·javascript·面试
小粉粉hhh8 小时前
React(二)——dom、组件间通信、useEffect
前端·javascript·react.js
索西引擎10 小时前
【React】key 属性:协调算法中的元素标识机制与最佳实践
前端·javascript·react.js
只会cv的前端攻城狮10 小时前
动态组件架构设计:从配置到事件驱动全链路解析
前端·vue.js
万敏10 小时前
Vue3 全栈实战第二周:Pinia + Vite + Router + axios 完整记录
vue.js·node.js·全栈
OpenTiny社区10 小时前
TinyEngine 2.11版本发布:AI 进一步融入画布,Vue 工程可一键转DSL
前端·vue.js·github
小雪_Snow10 小时前
JavaScript 中的三种常用事件
开发语言·前端·javascript