JS、Vue鼠标拖拽

JS、Vue鼠标拖拽_第1张图片

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

<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,javascript,vue.js)