0

I am trying to calculate the diistance from the bottom the the window to the current scroll position. I have used the following code ( LIVE DEMO ) :-

 $(window).scroll(function(){
   var height= $(document).height() - $(document).scrollTop();
   $(".height").html(height);
 });

The ouput when I scroll to the bottom must be 0. But, the output is something greater than 400. Please tell me how to fix it. Thanks in advance. Any help will be appreciated.

4

3 回答 3

3

您还应该考虑窗口高度。最后,微积分会为您返回这个问题的答案:可见区域的末端距离页面底部
有多少像素?

如果这适合您,那么此代码将执行此操作:

$(window).on("scroll", function() {
    var bottom = $(document).height() - $(window).height() - $(window).scrollTop();
    $(".height").text(bottom + "px from the bottom of the page");
});

演示

于 2013-10-11T17:10:04.553 回答
3

给你...小提琴

 $(window).scroll(function () {
     //for fiddle
     var height = $(document).height() - $(window).height() - $(window).scrollTop();

     //to test on real website
     //var height = $(document).height() - $(window).height()
     $(".height").html(height);
 });
于 2013-10-11T17:09:27.210 回答
0

因为$(document).height()$(window).height()是 consts !您想缓存它们而不是在每个滚动刻度上计算它们:

var _d= $(document).height() ;
var _w= $(window).height() ;
//you can also cache (if you want) $(window) , $('.height')


 $(window).scroll(function(){

     var height=_d - _w - $(window).scrollTop();
     $(".height").html(height);
 });

你不想要那些重复:

在此处输入图像描述

但是你需要这样做:

$(window).on('resize',function (){ _w= $(window).height() });
于 2013-10-11T17:18:39.190 回答