<template>
  <div>
    <div id="bottom">{{ stateBar }}</div>
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';

export default defineComponent({
  name: 'MouseSelect',
  data() {
    return {
      stateBar: '',
    };
  },
  methods: {
    mouseDownEvent(e: MouseEvent) {
      const posx = e.clientX;
      const posy = e.clientY;
      const div = document.createElement('div');
      div.className = 'tempDiv';
      div.style.left = `${e.clientX}px`;
      div.style.top = `${e.clientY}px`;
      document.body.appendChild(div);

      document.onmousemove = (ev: MouseEvent) => {
        div.style.left = `${Math.min(ev.clientX, posx)}px`;
        div.style.top = `${Math.min(ev.clientY, posy)}px`;
        div.style.width = `${Math.abs(posx - ev.clientX)}px`;
        div.style.height = `${Math.abs(posy - ev.clientY)}px`;
        this.stateBar = `MouseX: ${ev.clientX} <br/> MouseY: ${ev.clientY}`;
      };

      document.onmouseup = () => {
        div.parentNode?.removeChild(div);
        document.onmousemove = null;
        document.onmouseup = null;
      };
    },
  },
  mounted() {
    const stateBar = document.getElementById('bottom');
    if (stateBar) {
      stateBar.addEventListener('mousedown', this.mouseDownEvent);
    }
  },
  beforeUnmount() {
    const stateBar = document.getElementById('bottom');
    if (stateBar) {
      stateBar.removeEventListener('mousedown', this.mouseDownEvent);
    }
  },
});
</script>
<style>
* {
  padding: 0;
  margin: 0;
}

#bottom {
  position: absolute;
  bottom: 0px;
  width: 100%;
  height: 40px;
  border: 1px solid #000;
  background: #000;
  color: #fff;
}

.tempDiv {
  border: 1px dashed blue;
  background: #5a72f8;
  position: absolute;
  width: 0;
  height: 0;
  filter: alpha(opacity: 10);
  opacity: 0.1;
}
</style
代码优化改为vue3和Typescript并且修复存在的BUG !DOCTYPE HTML PUBLIC -W3CDTD HTML 401ENhttpwwww3orgTRhtml4strictdtdhtmlheadmeta http-equiv=Content-Type content=texthtml; charset=utf-8title鼠标框选效果titlestylepadding0;mar

原文地址: http://www.cveoy.top/t/topic/exky 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录