我遇到了jQuery滚动和粘滞按钮的问题。
我有code
$window.scroll(function() {
var $this = $(this);
var scrollTop = $this.scrollTop();
if ($buttonFilter.length > 0) {
if (scrollTop + windowHeight > buttonFilterFullSize) {
if ($buttonFilter.hasClass('fixed')) {
$buttonFilter.removeClass('fixed');
}
} else {
if (!$buttonFilter.hasClass('fixed')) {
$buttonFilter.addClass('fixed');
}
}
}
});
当隐藏所有折叠时它运行良好,但是当我打开它时,粘性按钮不能很好地工作,并且在我使用滚动时不会跟随。
我可以做些什么来改善我的代码?
答案 0 :(得分:1)
您应该使用$(document).height();
来获取文档高度而不是窗口(浏览器窗口)高度,并且您需要将其放在scroll事件中以在手风琴扩展时刷新值。
至于您需要总计scrollTop
和windowHeight
的条件。 scrollTop
为您提供了Y坐标,windowHeight
为您提供了窗口的高度,两者的加起来都是documentHeight
。
您的代码应如下所示:
$window.scroll(function() {
var $this = $(this);
var scrollTop = $this.scrollTop();
var documentHeight = $(document).height();
var windowHeight = $(window).height();
if ($buttonFilter.length > 0) {
if ( (scrollTop + windowHeight) === documentHeight) {
if ($buttonFilter.hasClass('fixed')) {
//do something....
}
} else {
if (!$buttonFilter.hasClass('fixed')) {
//do something....
}
}
}