Javascript Javascript中确定垂直滚动百分比的跨浏览器方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2387136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Cross-Browser Method to Determine Vertical Scroll Percentage in Javascript
提问by majelbstoat
How can I find out what percentage of the vertical scrollbar a user has moved through at any given point?
如何找出用户在任何给定点移动过的垂直滚动条的百分比?
It's easy enough to trap the onscrollevent to fire when the user scrolls down the page, but how do I find out within that event how far they have scrolled? In this case, the percentage particularly is what's important. I'm not particularly worried about a solution for IE6.
onscroll当用户向下滚动页面时触发事件很容易,但是我如何在该事件中找出他们滚动了多远?在这种情况下,百分比尤其重要。我并不特别担心 IE6 的解决方案。
Do any of the major frameworks (Dojo, jQuery, Prototype, Mootools) expose this in a simple cross-browser compatible way?
是否有任何主要框架(Dojo、jQuery、Prototype、Mootools)以简单的跨浏览器兼容方式公开这一点?
回答by Phil Ricketts
Oct 2016:Fixed. Parentheses in jsbin demo were missing from answer. Oops.
2016 年 10 月:已修复。答案中缺少 jsbin 演示中的括号。哎呀。
Chrome, Firefox, IE9+. Live Demo on jsbin
铬、火狐、IE9+。jsbin 上的现场演示
var h = document.documentElement,
b = document.body,
st = 'scrollTop',
sh = 'scrollHeight';
var percent = (h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100;
As function:
作为功能:
function getScrollPercent() {
var h = document.documentElement,
b = document.body,
st = 'scrollTop',
sh = 'scrollHeight';
return (h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100;
}
If you prefer jQuery(original answer):
如果您愿意jQuery(原始答案):
$(window).on('scroll', function(){
var s = $(window).scrollTop(),
d = $(document).height(),
c = $(window).height();
var scrollPercent = (s / (d - c)) * 100;
console.clear();
console.log(scrollPercent);
})
html{ height:100%; }
body{ height:300%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
回答by Eduardo
I think I found a good solution that doesn't depend on any library:
我想我找到了一个不依赖于任何库的好解决方案:
/**
* Get current browser viewpane heigtht
*/
function _get_window_height() {
return window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight || 0;
}
/**
* Get current absolute window scroll position
*/
function _get_window_Yscroll() {
return window.pageYOffset ||
document.body.scrollTop ||
document.documentElement.scrollTop || 0;
}
/**
* Get current absolute document height
*/
function _get_doc_height() {
return Math.max(
document.body.scrollHeight || 0,
document.documentElement.scrollHeight || 0,
document.body.offsetHeight || 0,
document.documentElement.offsetHeight || 0,
document.body.clientHeight || 0,
document.documentElement.clientHeight || 0
);
}
/**
* Get current vertical scroll percentage
*/
function _get_scroll_percentage() {
return (
(_get_window_Yscroll() + _get_window_height()) / _get_doc_height()
) * 100;
}
回答by Mark Bell
This should do the trick, no libraries required:
这应该可以解决问题,不需要库:
function currentScrollPercentage()
{
return ((document.documentElement.scrollTop + document.body.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight) * 100);
}
回答by toske
These worked for me perfectly in Chrome 19.0, FF12, IE9:
这些在 Chrome 19.0、FF12、IE9 中对我来说非常有效:
function getElementScrollScale(domElement){
return domElement.scrollTop / (domElement.scrollHeight - domElement.clientHeight);
}
function setElementScrollScale(domElement,scale){
domElement.scrollTop = (domElement.scrollHeight - domElement.clientHeight) * scale;
}
回答by majelbstoat
If you're using Dojo, you can do the following:
如果您使用的是 Dojo,则可以执行以下操作:
var vp = dijit.getViewport();
return (vp.t / (document.documentElement.scrollHeight - vp.h));
Which will return a value between 0 and 1.
这将返回一个介于 0 和 1 之间的值。
回答by timemachine3030
This question has been here for a long time, I know, but I stumbled onto it while trying to solve the same problem. Here is how I solved it, in jQuery:
我知道这个问题已经存在很长时间了,但是我在尝试解决同样的问题时偶然发现了它。这是我在 jQuery 中解决它的方法:
First, I wrapped the thing I wanted to scroll in a div (not semantic, but it helps). Then set the overflow and height on the wrapper.
首先,我将我想要滚动的内容包装在一个 div 中(不是语义,但它有帮助)。然后在包装纸上设置溢出和高度。
<div class="content-wrapper" style="overflow: scroll; height:100px">
<div class="content">Lot of content that scrolls</div>
</div>
Finally I was able to calculate the % scroll from these metrics:
最后,我能够根据这些指标计算滚动百分比:
var $w = $(this),
scroll_top = $w.scrollTop(),
total_height = $w.find(".content").height(),
viewable_area = $w.height(),
scroll_percent = Math.floor((scroll_top + viewable_area) / total_height * 100);
Here is a fiddle with working example: http://jsfiddle.net/prEGf/
这是一个带有工作示例的小提琴:http: //jsfiddle.net/prEGf/
回答by Dave
A Typescript implementation.
一个打字稿实现。
function getScrollPercent(event: Event): number {
const {target} = event;
const {documentElement, body} = target as Document;
const {scrollTop: documentElementScrollTop, scrollHeight: documentElementScrollHeight, clientHeight} = documentElement;
const {scrollTop: bodyScrollTop, scrollHeight: bodyScrollHeight} = body;
const percent = (documentElementScrollTop || bodyScrollTop) / ((documentElementScrollHeight || bodyScrollHeight) - clientHeight) * 100;
return Math.ceil(percent);
}
回答by gremo
My two cents, the accepted answer in a more "modern" way. Works back to IE9 using @babel/preset-env.
我的两分钱,以更“现代”的方式接受的答案。使用@babel/preset-env返回到 IE9 。
// utilities.js
/**
* @param {Function} onRatioChange The callback when the scroll ratio changes
*/
export const monitorScroll = onRatioChange => {
const html = document.documentElement;
const body = document.body;
window.addEventListener('scroll', () => {
onRatioChange(
(html.scrollTop || body.scrollTop)
/
((html.scrollHeight || body.scrollHeight) - html.clientHeight)
);
});
};
Usage:
用法:
// app.js
import { monitorScroll } from './utilities';
monitorScroll(ratio => {
console.log(`${(ratio * 100).toFixed(2)}% of the page`);
});
回答by Nadav B
First attach an event listener to some document you want to keep track
首先将事件侦听器附加到要跟踪的某个文档
yourDocument.addEventListener("scroll", documentEventListener, false);
Then:
然后:
function documentEventListener(){
var currentDocument = this;
var docsWindow = $(currentDocument.defaultView); // This is the window holding the document
var docsWindowHeight = docsWindow.height(); // The viewport of the wrapper window
var scrollTop = $(currentDocument).scrollTop(); // How much we scrolled already, in the viewport
var docHeight = $(currentDocument).height(); // This is the full document height.
var howMuchMoreWeCanScrollDown = docHeight - (docsWindowHeight + scrollTop);
var percentViewed = 100.0 * (1 - howMuchMoreWeCanScrollDown / docHeight);
console.log("More to scroll: "+howMuchMoreWeCanScrollDown+"pixels. Percent Viewed: "+percentViewed+"%");
}
回答by roryf
Using jQuery
使用 jQuery
$(window).scrollTop();
will get you the scroll position, you can then work out from there what the percentage is based on the window height.
将为您提供滚动位置,然后您可以从那里计算出基于窗口高度的百分比。
There is also a standard DOM property scrollTopthat you can use like document.body.scrollTophowever I'm not sure how this behaves cross-browser, I would assume if there are inconsistencies then the jQuery method accounts for these.
还有一个标准的 DOM 属性scrollTop,您可以像这样使用,document.body.scrollTop但是我不确定它在跨浏览器中的表现如何,我会假设如果存在不一致,那么 jQuery 方法会解决这些问题。

