滚动动画有问题。滚动动画后滚动页面时会发生跳转滚动。我怀疑滚动事件会重演,但我不确定。你能帮帮我吗?
$(document).ready(function(){
var offset;
var anchor = $("#navigation").offset().top;
$(window).bind('mousewheel', function (e) {
offset = $(window).scrollTop();
if (e.originalEvent.wheelDelta < 0) {
//mouse scroll down
console.log('Down: ' + offset + " " + anchor);
if (offset >= anchor) {
// if anchor has been scrolled, user can scroll further
// the problem ocuurs in this block
return true;
} else {
// animate to anchor( nav menu)
$("body, html").animate({
scrollTop: anchor + 1
}, 200);
$("#navigation").addClass("nav-fixed");
return false;
}
} else {
//mouse scroll up
if (offset < anchor) {
$("#navigation").removeClass("nav-fixed");
return true;
}
}});
});
JSFiddle:http://jsfiddle.net/0noms3cs/
非常感谢你!
答案 0 :(得分:1)
你的问题很简单。滚动事件一次又一次地触发。你在这个问题的原因背后的思路是正确的,你有大量的animate
事件被堆积起来,导致这种奇怪的行为。
您可以通过添加一个以 scrollInitialized
开头的布尔变量(例如false
)来解决此问题,并在滚动事件触发一次后翻转到true
这是改进的JS代码。注意:我只在if语句中添加了scrollInitialized
变量并对其进行了检查。
编辑:我还删除了内部 if-else
案例,因为没有必要使用此设计。
编辑2 :我原本误解了你想做什么。您需要做的是添加一个scrollLock
变量,该变量在动画期间仅设置为true
。在考虑了这个之后,我为你实现了它。这是Jsfiddle:
https://jsfiddle.net/04gaaapo/1/
这是新的JS代码:
$(document).ready(function () {
var scrollLock = false;
var offset;
var anchor = $("#navigation").offset().top;
$(window).bind('mousewheel', function (e) {
offset = $(window).scrollTop();
// if scroll is NOT locked and we are above the anchor
if (scrollLock === false && offset < anchor) {
if (e.originalEvent.wheelDelta < 0) {
// scrolling down
scrollLock = true;
// animate to anchor( nav menu)
$("body, html").animate({
scrollTop: anchor + 1
}, 200);
// unlock in 250ms
setTimeout(toggleLock, 250);
// add nav class
$("#navigation").addClass("nav-fixed");
} else if (e.originalEvent.wheelDelta > 0) {
// scrolling up
scrollLock = true;
// animate to top of page
$("body, html").animate({
scrollTop: 0
}, 200);
// unlock in 250ms
setTimeout(toggleLock, 250);
// remove nav class
$("#navigation").removeClass("nav-fixed");
}
}
});
function toggleLock() {
scrollLock = !scrollLock;
};
});