我在页面的顶部有一个菜单栏,希望当我滚动到页面顶部时,如果我继续向上滚动,菜单栏就会显示出来。
我使用jQuery编写了以下代码:
// listen for the scroll to show the top menu
var was_on_top = false;
$(function () {
$(window).bind("scroll", function (e) {
if ($(window).scrollTop() == 0) {
if ($('.menu').css('display') == "none" && was_on_top) {
$('.menu').slideDown();
} else {
was_on_top = true;
}
} else {
was_on_top = false;
}
});
});
但是当滚动到顶部时,滚动事件不会触发。有什么想法吗?
编辑:下面是可行的代码。在FF、Chrome和IE9上测试过。
// listen for the scroll to show the top menu
var was_on_top = false;
$(function () {
if (window.addEventListener) {
window.addEventListener('DOMMouseScroll', onMouseWheelSpin, false); // FireFox
window.addEventListener('mousewheel', onMouseWheelSpin, false); // Chrome
} else {
window.onmousewheel = onMouseWheelSpin;
}
});
function onMouseWheelSpin(event) {
if (!event) // IE sucks
event = window.event;
if ($(window).scrollTop() == 0 &&
(
event.detail < 0 // Firefox
||
(event.wheelDelta && (
(window.opera && event.wheelDelta < 0) // Opera
||
event.wheelDelta > 0 // IE
)
)
)
) {
if ($('.menu').css('display') == "none" && was_on_top) {
$('.menu').slideDown();
} else {
was_on_top = true;
}
} else {
was_on_top = false;
}
}