关于前端:控制盒子左右伸缩

39次阅读

共计 1710 个字符,预计需要花费 5 分钟才能阅读完成。

父组件

<template>
  <div
    :style="{'padding-left': moveInfo.width +'px',}"class="drag-class"
  >
    <div
      :style="{
        width: moveInfo.width + 'px',
        height: moveInfo.height + 'px',
      }"class="content-text"
    ></div>
    <div class="right"></div>

    <ChangeWidth
      ref="aa"
      @widthChange="changeWidth"
      @clearEvent="clearEvent"
      :left="moveInfo.width"
    />
  </div>
</template>
 
<script>
import ChangeWidth from "./ChangeWidth";
export default {components: { ChangeWidth},
  name: "demo",
  data() {
    return {
      moveInfo: {
        width: 400,
        height: 100,
      },
    };
  },
  methods: {
    // 扭转 drag 宽度尺寸
    changeWidth(width) {
      const newWidth = this.moveInfo.width + width;
      this.moveInfo.width = newWidth;
      // 设置 div 的最小宽度和最大宽度
      if (this.moveInfo.width <= 200) {
        this.moveInfo.width = 200;
        this.$refs.aa.mouseUp();}
      if (this.moveInfo.width >= 900) {
        this.moveInfo.width = 900;
        this.$refs.aa.mouseUp();}
    },

    // 革除鼠标事件
    clearEvent() {
      document.onmousemove = null;
      document.onmouseup = null;
    },
  },
};
</script>
<style lang="less" scoped>
.drag-class {
  position: relative;
  height: 100%;
  .content-text {
    position: absolute;
    left: 0;
    background-color: orange;
  }
  .right {
    margin-left: 5px;
    height: 100px;
    background-color: skyblue;
  }
}
</style>

子组件

<template>
  <!-- 拖动左边距扭转 div 宽度 -->
  <div
    class="x-handle"
    @mousedown="mouseDown"
    @mouseup="mouseUp"
    :style="{left: left}"
  ></div>
</template>
 
<script>
export default {
  name: "ChangeWidth",
  props: ["left"],
  data() {
    return {lastX: 0,};
  },

  methods: {mouseDown(event) {document.addEventListener("mousemove", this.mouseMove);
      this.lastX = event.screenX; // 鼠标指针绝对于屏幕的程度坐标
    },
    mouseMove(e) {
      let width = e.screenX - this.lastX;
      this.$emit("widthChange", width);
      this.lastX = e.screenX;
    },
    mouseUp() {
      this.lastX = 0;
      document.removeEventListener("mousemove", this.mouseMove);
      this.$emit("clearEvent");
    },
  },
};
</script>
<style lang="less" scoped>
.x-handle {
  width: 5px;
  cursor: e-resize;
  // background: #2866f0;
  height: 100%;
  position: absolute;
  top: 0;
}
</style>

正文完
 0