簡體   English   中英

如何計算點擊進度條x軸鼠標的位置?

[英]How to calculate where on progress bar x-axis mouse was clicked?

我正在嘗試計算用戶點擊進度條容器的百分比。 即:如果他們點擊中間它應該通過“50%”。 但隨着進度條的變化,我得到的結果不正確。

<template>
  <span class="progress"
        :style="{ width }"
        @click.prevent="onClickProgress($event)">
    <span class="elapsed" :style="{ width: completed }" ref="elapsed"></span>
    <span class="remainder" :style="{ width: remainder }"></span>
  </span>
</template>
<script>
export default {
  name: 'progress-bar',
  props: ['percent', 'width'],
  computed: {
    completed() {
      return `${this.percent}%`;
    },
    remainder() {
      return `${100 - this.percent}%`;
    },
  },
  methods: {
    onClickProgress($event) {
      // calculate where on progress bar click happened
      const width = $event.currentTarget.clientWidth;
      const elapsedWidth = this.$refs.elapsed.clientWidth;
      const offsetX =  elapsedWidth <  width ? elapsedWidth + $event.offsetX : $event.offsetX;
      const percent = Math.round((offsetX / width) * 100);


      this.$emit('onClickProgress', { percent });
    },
  },
};
</script>
<style lang="scss" scoped>
.progress {
  display: flex;
  justify-content: flex-start;
  flex-wrap: nowrap;
  align-items: center;
  margin: 0 1rem;
  cursor: pointer;

  .elapsed {
    display: inline-block;
    height: .5rem;
    background: #E41C69;
  }

  .remainder {
    display: inline-block;
    height: .5rem;
    background: #000;
  }
}
</style>

它與點擊的元素有關,因為我有兩個子元素用於經過和余數我認為鼠標事件給我這個元素的坐標而不是.progress欄這是我想要的。

    onClickProgress($event) {
      // calculate where on progress bar click happened
      const width = $event.currentTarget.clientWidth;
      const elapsedWidth = this.$refs.elapsed.clientWidth;
      const offsetX =  elapsedWidth <  width ? elapsedWidth + $event.offsetX : $event.offsetX;
      const percent = Math.round((offsetX / width) * 100);

      this.$emit('onClickProgress', { percent });
    },

這很棘手。

我認為問題是$ event.offsetX基於click的目標,可能是已經過去的或剩余的組件,所以你必須計算來自target和currentTarget的相對偏移量的偏移量:

  const offsetX = $event.offsetX + $event.target.offsetLeft - $event.currentTarget.offsetLeft;

這將為您提供父項中單擊的偏移量,這使您的百分比計算正確。

我的更新,雖然有點混亂,沙箱: https//codesandbox.io/s/llnmj5x7lz

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM