gpt4 book ai didi

javascript - 跨浏览器确定Javascript垂直滚动百分比的方法

转载 作者:IT王子 更新时间:2023-10-29 03:08:58 27 4
gpt4 key购买 nike

如何找出用户在任何给定点移动过的垂直滚动条的百分比?

当用户向下滚动页面时,很容易触发 onscroll 事件,但我如何在该事件中找出他们滚动了多远?在这种情况下,百分比尤为重要。我并不是特别担心 IE6 的解决方案。

是否有任何主要框架(Dojo、jQuery、Prototype、Mootools)以简单的跨浏览器兼容方式公开此内容?

最佳答案

Oct 2016: Fixed. Parentheses in jsbin demo were missing from answer. Oops.

Chrome、火狐、IE9+。 Live Demo on 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;

作为函数:

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;
}

如果您更喜欢 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>

关于javascript - 跨浏览器确定Javascript垂直滚动百分比的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2387136/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com