我有一个顶级菜单,当我滚动时淡入 - 并且当我不滚动时淡出。 当我不滚动时,它在1300ms内仍然可见,在此期间我希望它保持可见,以防我将鼠标悬停在它上面。
滚动上的淡入淡出效果很好,但如果我将鼠标悬停在它上面,它就不会保持可见。
这是我的代码:
$(function() {
$(window).scroll(function () {
var scrollTop = $(window).scrollTop();
if (scrollTop > 150) {
$('#top').fadeIn(400);
clearTimeout($.data(this, 'scrollTimer'));
$.data(this, 'scrollTimer', setTimeout(function () {
$('#top').fadeOut(400);
}, 1300));
}else{
clearTimeout($.data(this, 'scrollTimer'));
$('#top').fadeOut(400);
}
$('#top').hover(
function (e) {
var scrollTop = $(window).scrollTop();
if(scrollTop != 0){
$('#top').stop().animate({'opacity':'1'},400);
}
},
function (e) {
var scrollTop = $(window).scrollTop();
if(scrollTop != 0){
$('#top').stop().animate({'opacity':'0.2'},400);
}
}
);
});
});
body {height:3000px;}
ul, li {
list-style-type: none;
list-style: none;
text-decoration: none;
}
#top, #topStatic {
height:5%;
width: 92%;
max-width:1150px;
background:gray;
top: 0;
left:0;
right:0;
box-sizing: border-box;
margin: 0 auto;
}
#top {
position: fixed;
z-index:9999;
}
#top ul {
width:440px;
margin:0 auto;
height:100%;
}
#top li {
float: left;
padding: 2% 10px;
}
#top li:hover {
background-color: #D9D9D9;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav id="top" class="marginLeft">
<ul>
<li><a href="#">home</a></li>
<li><a href="#aboutus">about us</a></li>
<li><a href="#projects">projects</a></li>
<li><a href="#contact">contact</a></li>
</ul>
</nav>
非常感谢任何帮助!
答案 0 :(得分:2)
我修改了您的脚本,以便在全局范围内拥有scrollTimer
这样,它可以更容易地设置或清除。
我使用函数来避免重复代码过多。
看看!
;)
$(function() {
var scrollTimer;
function setTimer(){
scrollTimer = setTimeout(function () {
$('#top').fadeOut(400);
}, 1300);
}
function clearTimer(){
clearTimeout(scrollTimer);
}
$(window).scroll(function () {
var scrollTop = $(window).scrollTop();
if (scrollTop > 150) {
$('#top').fadeIn(400);
clearTimer();
setTimer();
}
$('#top').hover(
function (e) {
clearTimer();
var scrollTop = $(window).scrollTop();
if(scrollTop != 0){
$('#top').stop().animate({'opacity':'1'},400);
}
},
function (e) {
var scrollTop = $(window).scrollTop();
if(scrollTop != 0){
setTimer();
}
}
);
});
});
&#13;
body {height:3000px;}
ul, li {
list-style-type: none;
list-style: none;
text-decoration: none;
}
#top, #topStatic {
height:5%;
width: 92%;
max-width:1150px;
background:gray;
top: 0;
left:0;
right:0;
box-sizing: border-box;
margin: 0 auto;
}
#top {
position: fixed;
z-index:9999;
}
#top ul {
width:440px;
margin:0 auto;
height:100%;
}
#top li {
float: left;
padding: 2% 10px;
}
#top li:hover {
background-color: #D9D9D9;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav id="top" class="marginLeft">
<ul>
<li><a href="#">home</a></li>
<li><a href="#aboutus">about us</a></li>
<li><a href="#projects">projects</a></li>
<li><a href="#contact">contact</a></li>
</ul>
</nav>
&#13;