我正在以特定的文档高度停靠到视口顶部的导航,当它停靠时,它具有下拉动画。
$(document).scroll(function(){
var x = $(window).scrollTop();
if(x>=700){
$("header").addClass("fix");
if($("header").hasClass("fix")){
$("header").animate({top: '0'},500);
}
$("main").css("padding-top", "100px");
}
if(x<=300){
if($("header").hasClass("fix")){
$("main").removeAttr("style");
$("header").removeClass("fix");
}}
});
header{background:green}
main{height:2000px;background:yellow;}
#header{padding:20px; display: inline-flex;}
.fix{
width:100%;
position:fixed;
top:-100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header>
<div id="header">
<a href="http://stackoverflow.com">Stack overflow</a>
</div>
</header>
<main>
</main>
我的问题是,在滚动回到页面顶部并再次向下滚动页面后,导航弹出。它不会下降(显示动画(,我该如何修复?
https://jsfiddle.net/damiantoczek/rc05odu8/
(我自己写了该代码,而不是复制糊(
您可以使用普通CSS进行操作:
header {
top: -100px;
transition: top .5s;
}
header.fix{
width:100%;
position:fixed;
top: 0;
}
只需从JS
中删除animate
调用编辑:这是小提琴
作为 @sklingler93使用CSS过渡的答案似乎是最好的方法,OP的答案是:
- 当滚动事件触发了很多次功能时,您应该在
.animate(...)
之前使用.stop()
,以确保不排队动画。 - 您忘了在
if <300
语句中删除标头的样式属性。
这是您的代码的答案,因为有一些没有用的说明:https://jsfiddle.net/rc05odu8/2/
或仅修复您的代码:
$(document).scroll(function() {
var x = $(window).scrollTop();
if (x >= 700) {
$("header").addClass("fix");
$("header").stop().animate({
top: '0'
}, 500);
$("main").css("padding-top", "100px");
}
if (x <= 300) {
$("main").removeAttr("style");
$('header').removeAttr('style');
$("header").removeClass("fix");
}
});
我认为在这个片段...
if(x>=(a-100)){
$("header").addClass("fix");
if($("header").hasClass("fix")){
$("header").animate({top: '0'},500);
}
$("main").css("padding-top", "100px");
}
-
$("header").addClass("fix");
应该在if($("header").hasClass("fix"))
;
内 - 可能
$("main").css("padding-top", "100px");
也应该在if
内; - 您应该否定
if
表达式;
这样,您将拥有:
if(x>=(a-100))
{
if(!$("header").hasClass("fix"))
{
$("header").addClass("fix");
$("header").animate({top: '0'},500);
$("main").css("padding-top", "100px");
}
}
对我来说更有意义。
另外,您必须清除所有当滚动返回顶部时,动画应用的样式。
希望它有帮助。