【发布时间】:2018-02-21 08:39:14
【问题描述】:
使用 jQuery,我正在尝试制作一个类似于 this Wordpress plugin 的导航栏:当页面加载时,导航栏是隐藏/离屏的,当到达某个滚动位置时,它会向下滑动到固定位置,然后向上滑动到当用户向上滚动到顶部时,它的屏幕外位置。
我设法做到了,但是,时间完全错误:滚动后可能需要几秒钟才能出现菜单栏。向上滚动时更糟:起初我认为它根本不起作用,但有时在 15 秒甚至更长时间后,它最终会向上移动。
这是我的代码:
$(window).scroll(function() {
var scrollposition = $(window).scrollTop();
if (scrollposition > 100) {
$("#main_navigation").animate({
top: "0px"
}, 600);
};
if (scrollposition < 100) {
$("#main_navigation").animate({
top: "-82px"
}, 400);
};
});
html,
body {
margin: 0;
height: 100%;
}
.content {
height: 200%;
background: #fda;
padding: 5em 3em;
}
nav#main_navigation {
position: fixed;
z-index: 1;
top: -82px;
width: 100%;
background: #fff;
height: 54px;
border-bottom: 1px solid #eee;
}
.logo {
display: inline-block;
position: relative;
top: 50%;
left: 2em;
margin: 0;
width: 36px;
transform: translateY(-50%);
}
nav#main_navigation ul {
position: relative;
top: 50%;
margin: 0;
transform: translateY(-50%);
display: inline-block;
list-style: none;
float: right;
margin-right: 0.8em;
}
nav#main_navigation li {
display: inline-block;
margin-right: 1.2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav id="main_navigation">
<div class="logo">(logo)</div>
<ul>
<li><a href="#">Welcome</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
<div class="content">
<p>This is the content. Scroll down at least 100px to make the navbar appear. This should take 0.6 seconds, but takes much longer.</p>
<p>Then scroll back up to make the navbar disappear again. This should only take 0.4 seconds...</p>
</div>
我想这可能与必须处理的滚动事件过多有关,但我不知道如何避免或过滤它。还是有其他原因?
【问题讨论】:
标签: jquery css jquery-animate