我试图将.site-header
隐藏在滚动条上,并使其在闲置几秒钟后重新出现。
我在这里找到了最多的答案:How to hide a Div when the scroll bar is moving with jQuery?
var $header = $(".site-header");
var opacity = $header.css("opacity");
var scrollStopped;
var fadeInCallback = function () {
if (typeof scrollStopped != 'undefined') {
clearInterval(scrollStopped);
}
scrollStopped = setTimeout(function () {
$header.animate({ opacity: 1 }, "slow");
}, 500);
}
$(window).scroll(function () {
if (!$header.is(":animated") && opacity == 1) {
$header.animate({ opacity: 0 }, "slow", fadeInCallback);
} else {
fadeInCallback.call(this);
}
});
$('.menu-toggle').on('click', function(){
$('.menu-toggle').addClass('activated');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
<section style="height:5000px;">
<div class="site-header" style="position:fixed; top:5px; left:5px; width:200px; height:100px; display:block; background:#000; opacity:1;">
<button class="menu-toggle">Menu</button>
<nav class="nav-primary">
<ul>
<li>Menu item 1</li>
<li>Menu item 2</li>
<li>Menu item 3</li>
</ul>
</nav>
</div>
</section>
通过单击
nav
激活button
但是,
nav
嵌套在.site-header
内,这意味着在激活菜单时,它仍会在滚动中消失。我想知道如何更改此javascript,以便将
.activated
类应用于button
时,即使在滚动时nav
仍然可见。这是小提琴https://jsfiddle.net/fwa16eok/
非常感谢!
最佳答案
在淡出动画调用之前添加!$menu.is(":active")
var $menu = $("#menu");
var opacity = $menu.css("opacity");
var scrollStopped;
var fadeInCallback = function () {
if (typeof scrollStopped != 'undefined') {
clearInterval(scrollStopped);
}
scrollStopped = setTimeout(function () {
$menu.animate({ opacity: 1 }, "slow");
}, 2000);
}
$(window).scroll(function () {
if (!$menu.is(":active") &&!$menu.is(":animated") && opacity == 1) {
$menu.animate({ opacity: 0 }, "slow", fadeInCallback);
} else {
fadeInCallback.call(this);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.3/jquery.min.js"></script>
<section style="height:5000px;">
<div id="menu" style="position:fixed; top:5px; left:5px; width:200px; height:100px; display:block; background:#000; opacity:1;"></div>
</section>