每当用户滚动页面时,我想在页面底部放置一个元素。就像“固定位置”一样,但是我不能使用“位置:固定” css,因为我的客户的许多浏览器都不支持。
我注意到jquery可以获取当前视口的顶部位置,但是如何获取滚动视口的底部位置呢?
所以我问如何知道:$(window).scrollBottom()
Answers:
var scrollBottom = $(window).scrollTop() + $(window).height();
Top是从文档Top到可见窗口的垂直像素数Top。与scroll完全相反Top,scrollBottom应该测量从文档Bottom到可见窗口的垂直像素数Bottom(即下面的Alfred回答)。什么这给出了从文档垂直像素的#_top_至可见的窗口Bottom。可以肯定地说,这很有用,尽管不能称之为ScrollBottom的反义词(我知道这是一个明显的答案,但对于像我这样的未来读者而言)
我要说,与scrollTop直接相反的scrollBottom应该是:
var scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();
这是一个对我有用的小丑陋测试:
// SCROLLTESTER START //
$('<h1 id="st" style="position: fixed; right: 25px; bottom: 25px;"></h1>').insertAfter('body');
$(window).scroll(function () {
var st = $(window).scrollTop();
var scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();
$('#st').replaceWith('<h1 id="st" style="position: fixed; right: 25px; bottom: 25px;">scrollTop: ' + st + '<br>scrollBottom: ' + scrollBottom + '</h1>');
});
// SCROLLTESTER END //
为了将来,我将scrollBottom制成了一个jquery插件,可以使用与scrollTop相同的方式(即,您可以设置一个数字,它将从页面底部滚动该数量并从底部返回像素数量。页面的像素数,或者,如果没有提供数字,则返回页面底部的像素数)
$.fn.scrollBottom = function(scroll){
if(typeof scroll === 'number'){
window.scrollTo(0,$(document).height() - $(window).height() - scroll);
return $(document).height() - $(window).height() - scroll;
} else {
return $(document).height() - $(window).height() - $(window).scrollTop();
}
}
//Basic Usage
$(window).scrollBottom(500);
这将滚动到最顶部:
$(window).animate({scrollTop: 0});
这将滚动到最底部:
$(window).animate({scrollTop: $(document).height() + $(window).height()});
..如有必要(用引号引起来),将窗口更改为所需的容器ID或类。
overflow-y: auto使其实际滚动到文本底部(超出div的高度)?
scrollHeight-参见: stackoverflow.com/q/7381817
// Back to bottom button
$(window).scroll(function () {
var scrollBottom = $(this).scrollTop() + $(this).height();
var scrollTop = $(this).scrollTop();
var pageHeight = $('html, body').height();//Fixed
if ($(this).scrollTop() > pageHeight - 700) {
$('.back-to-bottom').fadeOut('slow');
} else {
if ($(this).scrollTop() < 100) {
$('.back-to-bottom').fadeOut('slow');
}
else {
$('.back-to-bottom').fadeIn('slow');
}
}
});
$('.back-to-bottom').click(function () {
var pageHeight = $('html, body').height();//Fixed
$('html, body').animate({ scrollTop: pageHeight }, 1500, 'easeInOutExpo');
return false;
});