鼠标点击移动事件

2022-03-17  本文已影响0人  FrankFang7
<template>
  <div id="box">
    <div id="line" :style="style"></div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      x: 0,
      y: 0,
      style: {}
    }
  },
  methods: {
    mouseDown (e) {
      e = e || window.Event
      if (!this.x && !this.y) {
        this.x = e.pageX
        this.y = e.pageY
      } else {
        this.x = 0
        this.y = 0
        this.style = {}
      }
    },
    mouseMove (e) {
      if (this.x && this.y) {
        const line = document.getElementById('line')
        line.classList = ['line']
        e = e || window.Event
        const style = {
          left: this.x + 'px',
          top: this.y + 'px',
          width: e.pageX - this.x + 'px',
          height: e.pageY - this.y + 'px'
        }
        this.style = style
      }
    }
  },
  mounted () {
    /* 这里是给整个页面添加了一个鼠标移动的监听事件 e为事件对象 */
    const box = document.getElementById('box')
    box.addEventListener('mousemove', this.mouseMove)
    box.addEventListener('mousedown', this.mouseDown)
  },
  beforeDestroy () {
    document.removeEventListener('mousemove', this.mouseMove)
    document.removeEventListener('mousedown', this.mouseDown)
  }
}
</script>

<style>
#box {
  height: 100vh;
  width: 100%;
  position: relative;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 0;
}
#box #line {
  position: fixed;
  border: 1px solid red;
}
</style>
上一篇 下一篇

猜你喜欢

热点阅读