计算从底部到当前位置的距离

时间:2013-10-11 16:55:34

标签: javascript jquery

我正在尝试计算从窗口底部到当前滚动位置的距离。我使用了以下代码(LIVE DEMO): -

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

滚动到底部时的输出必须 0 。但是,输出大于400.请告诉我如何解决它。提前致谢。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:3)

你去...... fiddle

 $(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);
 });

答案 1 :(得分:3)

你应该考虑窗户高度。最后,微积分会给你这个问题的答案:
远离页面底部的可见区域的末端有多少像素?

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

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

Demo

答案 2 :(得分:0)

由于$(document).height()$(window).height()是有争议的! 你想要缓存它们而不是每个滚动刻度线计算它们:

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

你不想要那些重复:

enter image description here

然而你需要这样做:

$(window).on('resize',function (){ _w= $(window).height() });