问题:我正在尝试完成以下动画:当页面在移动设备中加载时,我想显示 ID 为“sub-header”的 div,但只要用户滚动超过我想在页面下方 50px 处隐藏子标题。最后,如果用户在页面上随时向上滚动 60px,我希望子标题显示为 .show
我在下面的代码中看到了什么: 该页面隐藏了菜单,但是当我向上滚动时,它在我停止滚动后多次显示和隐藏。
JQuery:
var newScroll = 0;
var subHeaderPosition = true;
var currentScroll = 0;
$(window).scroll(function () {
currentScroll = $(window).scrollTop();
if ($(window).width() < 779) {
if (currentScroll > 50 && subHeaderPosition) {
console.log("Current Scroll position: " + currentScroll);
console.log("Scroll should hide");
$("#sub-header").hide(300);
subHeaderPosition = false;
newScroll = $(window).scrollTop();
console.log("New Scroll position: " + newScroll);
} else if ((currentScroll - 60) < newScroll && !subHeaderPosition) {
console.log("Scroll position: " + currentScroll);
console.log("Scroll should show Sub-Header");
$("#sub-header").show(300);
subHeaderPosition = true;
newScroll = $(window).scrollTop();
} else {
newScroll = $(window).scrollTop();
}
}
});
更新: 添加更多日志后,我现在可以知道我的 newscroll 和 currentscroll 总是以相同的数字结尾,这为我指明了正确的方向。一旦我有了解决方案,我会发布一个解决方案,或者如果有人想出解决方案,我会洗耳恭听。
最佳答案
你可以用它来解决问题
$(function(){
$(window).on('scroll', function(){
if($(window).scrollTop() >= 50){
$('header').addClass('hide');
}
else if($(window).scrollTop() <= 60){
$('header').removeClass('hide');
}
});
});
关于javascript - 根据滚动位置显示/隐藏子标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40851978/