vue中仿window系统左键画框效果

vue中仿window系统左键画框效果

一、代码原理

通过鼠标按下,移动,抬起事件来操作

  1. 首先鼠标按下来获取当前按下的位置
  2. 然后通过判断来进行鼠标移动的操作,判断鼠标是否按下,按下时才能执行鼠标移动的事件
  3. 在移入过程中的根据框的多个形式来判断画框操作
  4. 最后松开时恢复到原有的样子

二、上代码

<template>
  <div>
    <div class="cc" style="border:1px solid red;width:100%;height:100vh"  @mousedown="dian" @mousemove="yi" @mouseup="li">
    <div
      id="container"
      v-bind:style="{backgroundColor:back,
            height:h+'px',
            width:w+'px',
            position:'absolute',
            left:left+'px',
            top:top+'px',
            opacity:0.2,
            border:len+'px dashed #000'}"
    ></div>
    </div>
  </div>
</template>
 
<script>
export default {
  data() {
    return {
      py: "", //开始y轴的位置
      px: "", //开始x轴的位置
      back: "#31676f", //框框背景颜色
      h: "", //框框的高度控制
      w: "", //框框的宽度控制
      top: "", //框框的位置控制
      left: "", //框框的位置控制
      len: 0 //框框的边框
    };
  },
  methods: {
    dian(event) {
      // console.log(event);
      this.px = event.pageX; //获取x坐标
      this.py = event.pageY; //获取y坐标
    },
    yi(event) {
      if (this.px == "" || this.py == "") {
        return;
      }
      var px1 = this.px;
      var px2 = this.py;
      this.left = event.pageX;
      this.top = event.pageY;
      this.h = this.top - this.py;
      this.w = this.left - this.px;
      var hc = -this.h;
      var wc = -this.w;
      this.len = 1;
      this.back = "#31676f";
      if (this.h < 0 && this.w >= 0) {
        this.h = hc;
        this.left = px1;
      } else if (this.h >= 0 && this.w < 0) {
        this.w = wc;
        this.top = px2;
      } else if (this.h < 0 && this.w < 0) {
        this.h = hc;
        this.w = wc;
      } else {
        this.left = this.px;
        this.top = this.py;
      }
      if (this.w < 0) {
        this.w = 0 - this.w;
      }
      if (this.h < 0) {
        this.h = 0 - this.h;
      }
    },
    li() {
      //鼠标离开时数据恢复成原来的样子
      this.px = "";
      this.py = "";
      this.h = "";
      this.w = "";
      this.top = "";
      this.left = "";
      this.len = 0;
      this.back = "";
    }
  }
};
</script>
<style>
</style>

三、心得

非常好玩的一个小东西,可以加在很多的demo里面,代码都非常简单,一看就懂,希望对你有所帮助

猜你喜欢

转载自blog.csdn.net/qyp_1/article/details/106276665