【问题标题】:Calculating how many pixels user has scrolled down page计算用户向下滚动页面的像素数
【发布时间】:2018-12-04 02:58:03
【问题描述】:

我想知道用户从顶部向下滚动了我的页面有多少像素。因此,上面看不到的像素数加上当前视口中可见的像素数。

对于 Jquery,我使用的是 $(window).scrollTop(),它在滚动到页面底部后显示 612 像素,但 $(document).height() 报告的总高度为 1276 像素。

当我到达页面底部时,我想知道的数字将是 1276。

希望这是有道理的。

【问题讨论】:

  • Well top 是 612.... 而文档的高度使它成为..... 1276. scrollTop 不可能等于文档的高度。

标签: javascript


【解决方案1】:

听起来你想要得到的是窗口当前 Y 偏移的底部。

这可以通过将窗口的scrollTop()innerHeight 相加来计算:

$(window).scrollTop() + window.innerHeight

$(window).scroll(function() {
  $("#scrollTop").text($(window).scrollTop() + window.innerHeight);
  $("#docHeight").text($(document).height());
}).scroll();
body {height: 2500px;}
div {position: fixed; top: 0; left: 0;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <span>scrollTop:</span> <span id="scrollTop"></span>
  <br>
  <span>document Height:</span> <span id="docHeight"></span>
</div>

【讨论】:

  • 我看到你的代码在 sn-p 中工作,但是当我把它放到它自己的页面中时,scrollTop 数字与 document Height 相同,然后在滚动时增加。
  • @DanielWilliams 哎呀。我使用了$(this) 而不是$(window)(这在我的示例中有效,因为this window)。我相信我的编辑应该可以解决这个问题。
  • 我也捡到了,但结果还是和我之前的评论一样。
【解决方案2】:

要计算用户从最顶部开始垂直滚动页面的像素数,在 JavaScript 中,我们将探测 window.pageYOffset,或者在旧版本的 IE 中,其中之一document.body.scrollTop 的几个变体,无论支持哪个属性:

var scrollTop = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop

使用 jQuery 代替,相当于:

var scrollTop = $(window).scrollTop()

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<body>

<div style="height:1000px"></div>

<p id="output" style="position:fixed; left:0; top:0; padding:10px; font-weight:bold">
	You have scrolled the page by:
</p>

<script>

var output = document.getElementById('output')

window.addEventListener("scroll", function(){
	var scrollTop = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop;
	output.innerHTML = 'You have scrolled the page by: ' + scrollTop +'px'

}, false)

</script>




<script>

/* ### jQuery version below. Uncomment to see: ### */

/*

var $output = $('#output')

$(window).on('scroll', function(){
	var scrollTop = $(window).scrollTop()
	$output.html( 'You have scrolled the page by: ' + scrollTop +'px' )
})

*/

</script>


</body>

【讨论】:

    猜你喜欢
    • 2011-05-04
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    • 2015-05-26
    • 2023-04-08
    • 1970-01-01
    • 2014-10-02
    • 1970-01-01
    相关资源
    最近更新 更多