我试图计算从窗口底部到当前滚动位置的距离。我已经使用以下代码(LIVE DEMO): -计算从底部到当前位置的距离
$(window).scroll(function(){
var height= $(document).height() - $(document).scrollTop();
$(".height").html(height);
});
当我滚动至底部必须是的输出中。但是,输出大于400.请告诉我如何解决它。提前致谢。任何帮助将不胜感激。
我试图计算从窗口底部到当前滚动位置的距离。我已经使用以下代码(LIVE DEMO): -计算从底部到当前位置的距离
$(window).scroll(function(){
var height= $(document).height() - $(document).scrollTop();
$(".height").html(height);
});
当我滚动至底部必须是的输出中。但是,输出大于400.请告诉我如何解决它。提前致谢。任何帮助将不胜感激。
你去那里... 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);
});
你应该在藏汉占窗口高度。最后,微积分将回答你这个问题的答案:
有多少像素是可见区域的末端远离页面的底部?
如果适合你OK,那么这段代码将做到这一点:
$(window).on("scroll", function() {
var bottom = $(document).height() - $(window).height() - $(window).scrollTop();
$(".height").text(bottom + "px from the bottom of the page");
});
由于$(document).height()
和$(window).height()
是consts! 要缓存他们,而不是他们calc下每一卷滴答:
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() });
其实,更好的答案是不会使用jQuery :) – gustavohenke
你的答案同样好..但不幸的是,不得不打勾1最佳答案 – h2O
NP,由你决定最适合。 – gustavohenke