Get percentage of scroll position

前端 未结 2 1591
时光说笑
时光说笑 2021-01-07 11:59

The problem:

What would be the mathematical formula to calculate (regardless of the scrollHeight of the document) how far the bottom of the scrollbar i

2条回答
  •  无人及你
    2021-01-07 12:24

    Returns a number between 0 to 100 relative to scroll position:

    document.onscroll = function(){ 
      var pos = getVerticalScrollPercentage(document.body)
      document.body.innerHTML = "" + Math.round(pos) + "%"
    }
    
    function getVerticalScrollPercentage( elm ){
      var p = elm.parentNode
      return (elm.scrollTop || p.scrollTop) / (p.scrollHeight - p.clientHeight ) * 100
    }
    body{ height:2000px }
    span{ position:fixed; font:5em Arial; color:salmon; }


    ● Difference between scrollHeight & clientHeight

提交回复
热议问题