关于javascript:写一个-拖拽进度组件

41次阅读

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

<template>
  <div class="tool-bar" id="toolBar">
    <div class="color-bar" id="colorBar">
      <span class="mic-btn" id="micBtn"></span>
    </div>
  </div>
</template>
<script>
export default {data() {
    return {
      colorBar: null,
      isTarget: false,
      originalStart: 0,
      originalEnd: 0,
      start: 0,
      end: 0,
      percentage: 0,
      totalWidth: 266,
    }
  },
  mounted() {this.colorBar = document.getElementById("colorBar")
    this.toolBar = document.getElementById("toolBar")
    document.onmousedown = this.onmousedownEvent
    document.onmouseup = this.onmouseupEvent
    document.onmousemove = this.onmousemoveEvent
    document.onclick = this.onclickEvent
    let rect = this.toolBar.getBoundingClientRect()
    this.originalStart = rect.left
    this.originalEnd = rect.left + this.totalWidth
  },
  methods: {onmousedownEvent(e) {if (e.target.id === "micBtn") {this.isTarget = true}
    },
    onmousemoveEvent(e) {if (this.isTarget) {let { clientX} = e
        if (clientX > this.originalEnd) {this.colorBar.style.width = "100%"} else if (clientX < this.originalStart) {this.colorBar.style.width = "0%"} else {
          this.percentage = ((clientX - this.originalStart) /
            this.totalWidth
          ).toFixed(2)
          this.colorBar.style.width = this.percentage * 100 + "%"
        }
      }
    },
    onmouseupEvent(e) {if (this.isTarget) {
        this.isTarget = false
        this.$emit("percentChange", this.percentage)
      }
    },
    onclickEvent(e) {
      let target = e.target.id
      if (target === "toolBar" || target === "colorBar") {let { clientX} = e
        this.percentage = ((clientX - this.originalStart) /
          this.totalWidth
        ).toFixed(2)
        this.colorBar.style.width = this.percentage * 100 + "%"
        this.$emit("percentChange", this.percentage)
      }
    },
  },
}
</script>
<style lang="scss" scoped>
.tool-bar {
  width: 266px;
  margin-left: 15px;
  height: 5px;
  background: #ebebeb;
  border-radius: 3px;
  position: relative;
  .color-bar {
    position: absolute;
    height: 5px;
    top: 0;
    left: 0;
    border-radius: 3px;
    background: linear-gradient(180deg, #4edc66 0%, #00c55d 100%);
    width: 0%;
  }
  .mic-btn {
    width: 12px;
    height: 12px;
    background: #ffffff;
    box-shadow: 0px 0px 4px 0px rgba(0, 197, 93, 0.63);
    border: 1px solid #00c55d;
    position: absolute;
    top: 50%;
    right: 0;
    transform: translateY(-50%);
    border-radius: 50%;
    cursor: pointer;
  }
}
</style>

正文完
 0