Determine click position on progress bar?

前端 未结 8 1863
傲寒
傲寒 2021-02-08 19:38

Is it possible to determine the value/position of a user\'s click on a progress bar using plain javascript?

Currently, I can detect a click on the element but can only g

8条回答
  •  甜味超标
    2021-02-08 20:26

    The top voted answer is not actually going to work universally. This is because the you have to consider all the offsetLeft of all the offsetParents. Here is an improved answer. I hope it helps.

    __addProgressBarListener () {
          document.getElementById('video-player-progress-bar').addEventListener('click', function (e) {
            let totalOffset = this.offsetLeft
            let parent = this.offsetParent
            const maximumLoop = 10
            let counter = 0
            while (document.body !== parent && counter < maximumLoop) {
              counter += 1
              totalOffset += parent.offsetLeft
              parent = parent.offsetParent
            }
            const x = e.pageX - totalOffset // or e.offsetX (less support, though)
            const clickedValue = x / this.offsetWidth
            console.log('x: ', x)
            console.log('clickedValue: ', clickedValue)
          })
        },
    

提交回复
热议问题