在 JavaScript 中按给定的垂直滚动百分比滚动
Scroll by given vertical scroll percentage in JavaScript
我有 X
和 Y
百分比滚动值(值从 0 到 100),我想将页面滚动到该位置。我从 API 电话中收到百分比值。
function scrollPageByGivenPercentage(percentageX, percentageY) {
// ... scroll by percentage ...
//window.scrollTo(percentageX, percentageY);
}
上面的函数以像素为单位滚动,但它没有完成这项工作。我尝试使用的是:
function scrollPageByGivenPercentage(percentageX, percentageY) {
var yScrollInPx = document.body.documentElement.clientHeight * percentageY;
window.scrollTo(0, yScrollInPx);
}
我的猜测是 clientHeight
是错误的 属性。也尝试了 offsetHeight
。
我从这个question得到计算百分比:
我有这个函数来接收当前滚动值的百分比:
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;
}
获取文档的总高度,在 px
中计算出您需要的百分比,然后将其应用于 window.scrollTo()
。试试这个:
var scrollYPercent = 0.25;
var scrollYPx = document.documentElement.scrollHeight * scrollYPercent;
window.scrollTo(0, scrollYPx);
html, body { height: 1000px; }
p { margin-top: 400px; }
<p>Note the scroll position -></p>
我有 X
和 Y
百分比滚动值(值从 0 到 100),我想将页面滚动到该位置。我从 API 电话中收到百分比值。
function scrollPageByGivenPercentage(percentageX, percentageY) {
// ... scroll by percentage ...
//window.scrollTo(percentageX, percentageY);
}
上面的函数以像素为单位滚动,但它没有完成这项工作。我尝试使用的是:
function scrollPageByGivenPercentage(percentageX, percentageY) {
var yScrollInPx = document.body.documentElement.clientHeight * percentageY;
window.scrollTo(0, yScrollInPx);
}
我的猜测是 clientHeight
是错误的 属性。也尝试了 offsetHeight
。
我从这个question得到计算百分比:
我有这个函数来接收当前滚动值的百分比:
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;
}
获取文档的总高度,在 px
中计算出您需要的百分比,然后将其应用于 window.scrollTo()
。试试这个:
var scrollYPercent = 0.25;
var scrollYPx = document.documentElement.scrollHeight * scrollYPercent;
window.scrollTo(0, scrollYPx);
html, body { height: 1000px; }
p { margin-top: 400px; }
<p>Note the scroll position -></p>