获取滚动位置百分比

获取滚动位置百分比

本文介绍了获取滚动位置百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要计算的数学公式是什么(与文档的
scrollHeight 无关) ),滚动条的底部距离其总底部(即页面的末尾)有多远。因此,例如,当滚动条位于顶部时,我想说它的底部到文档底部的距离为 0%,并且当它完全滚动时一路(垂直),将是 100%

What would be the mathematical formula to calculate (regardless of thescrollHeight of the document) how far the bottom of the scrollbar is from it's total bottom (which would be the end of the page). So, for example, when the scrollbar is at the top, I would say the distance in percentages of the bottom of it, from the bottom of the document, would be 0%, and when it's totally scrolled all the way (vertically), it would be 100%.

我的目标是计算底部和底部之间的相对于视口的特定位置(假设为 3%)之间有多少像素。同样,文档高度应该什么也没有。 3%是相对于视口的3%。

My goal is to calculate how many pixels there are between the bottom and a specific position which is, let's say 3%, relative to the viewport, above that bottom. Again, the document height should mean nothing. 3% are 3% if it's relative to the viewport.

var P              = 3 // in %
var totalHeight    = document.documentElement.scrollHeight;
var viewportHeight = document.documentElement.clientHeight;


推荐答案

返回介于 0之间的数字 100 相对于滚动位置:


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

document.onscroll = function(){
  var pos = getVerticalScrollPercentage(document.body)

  document.body.innerHTML = "<span>" + Math.round(pos) + "%<span>"
};

function getVerticalScrollPercentage( elm ){
    var p = elm.parentNode,
        pos = (elm.scrollTop || p.scrollTop) / (p.scrollHeight - p.clientHeight ) * 100

    return pos
}
body{ height:2000px }
span{ position:fixed; font:5em Arial; color:salmon; }

● Different between scrollHeight & clientHeight

这篇关于获取滚动位置百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 07:08