Determine click position on progress bar?

前端 未结 8 1855
傲寒
傲寒 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:07

    I tested your project, try this solution:

    document.getElementById('progressBar').addEventListener('click', function (e) {
        var x = e.pageX - this.offsetLeft;
        
        //Uncomment the following line to activate alert
        //alert('Current position: ' + document.getElementById('progressBar').position);
        
        //Save position before the click
        var startPos = document.getElementById('progressBar').position;
        
        //Convert x value to progress range [0 1]
        
        var xconvert = x/300; //cause width is 300px and you need a value in [0,1] range
        var finalx = (xconvert).toFixed(1); //round up to one digit after coma
        
        //Uncomment the following line to activate alert
        //alert('Click value: ' + finalx);
      
        //If you don't want change progress bar value after click comment the following line
        document.getElementById('progressBar').value = finalx;
        
        document.getElementById('result').innerHTML = ('Start position: ' + startPos + "

    "); document.getElementById('result').innerHTML += ('Current position: ' + document.getElementById('progressBar').position + "
    "); document.getElementById('result').innerHTML += ('Current value: ' + document.getElementById('progressBar').value + "

    "); document.getElementById('result').innerHTML += ('Real click value: ' + xconvert + "
    "); document.getElementById('result').innerHTML += ('Current value set in progressbar: ' + finalx + "
    "); });
    #progressBar {
        width:300px;
    }
    
    

    • I set your progress bar width to 300px (you can change it)
    • Get position x in progress bar
    • Convert x position range from [0,300] to [0,1]
    • Change value inside progress bar

    Outputs:

    • Start Position
    • Current Position and Value (after click)
    • Real click value (not rounded up)
    • Value set in progressbar (rounded up)

    Working demo: http://jsfiddle.net/Yeti82/c0qfumbL

    Thanks to bobbyrne01 for update corrections!

提交回复
热议问题