javascript - 在 JavaScript 中按给定的垂直滚动百分比滚动

标签 javascript jquery scroll cross-browser

我有 XY 滚动百分比值(值范围从 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>

关于javascript - 在 JavaScript 中按给定的垂直滚动百分比滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60056201/

相关文章:

html - css position absolute and fixed 无法正常工作

javascript - 使用jquery从href标签中提取值

jquery - 为什么代码在jsfiddle中中断

javascript - 如何从复选框中获取值

javascript - 使用InputMask html(jqueryl或js)强制html输入中的小数?

javascript - 应用过滤器后 jQuery 调整窗口大小

html - 停止不必要的内容滚动

javascript - 使用jquery向下滚动到#lower div

javascript - 如何从 Firefox 扩展中捕获页面标题的变化

javascript - 在 Javascript 中查找模式的最简单方法