jQuery animate 仅正确运行一次,然后开始表现异常
jQuery animate runs correctly only once, then starts behaving strangely
我有以下 JavaScript/jQuery 代码。我看不出它有任何问题,但它无法正常工作。
$(document).ready(function(){
$(window).scroll(function(){
if($(window).scrollTop() > 0) {
$("#forumHeader").animate({top: '250px'});
}
else
{
$("#forumHeader").animate({top: '60px'});
}
});
});
#forumHeader
{
position: absolute;
top: 60px;
left: 0%;
height: 100px;
width: 200px;
color: white;
background-color: red;
}
#content
{
height: 1000px;
background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="forumHeader">Forum Header</div>
<div id="content">Some content here</div>
我第一次向下滚动时,它正常工作并且动画#forumHeader top: 250px。但是当我再次向上滚动时,它可能需要几秒钟才能动画回到顶部:60px。有时它来回变化,有时它可能什么都不做。问题是什么?请帮忙..
我会使用 jQuery 添加和删除 class,然后使用 CSS 转换
$(document).ready(function(){
// EDIT - Move the selector outside of the scroll event as suggested
var header = $("#forumHeader");
$(window).scroll(function(){
if($(window).scrollTop() > 0) {
header.addClass('slide');
} else {
header.removeClass('slide');
}
});
});
#forumHeader{
top: 60px;
-webkit-transition: top 500ms ease-out ;
-moz-transition: top 500ms ease-out ;
-o-transition: top 500ms ease-out ;
transition: top 500ms ease-out ;
}
#forumHeader.slide{
top: 250px;
}
#content
{
height: 1000px;
background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="forumHeader">Forum Header</div>
<div id="content">Some content here</div>
希望对您有所帮助
我有以下 JavaScript/jQuery 代码。我看不出它有任何问题,但它无法正常工作。
$(document).ready(function(){
$(window).scroll(function(){
if($(window).scrollTop() > 0) {
$("#forumHeader").animate({top: '250px'});
}
else
{
$("#forumHeader").animate({top: '60px'});
}
});
});
#forumHeader
{
position: absolute;
top: 60px;
left: 0%;
height: 100px;
width: 200px;
color: white;
background-color: red;
}
#content
{
height: 1000px;
background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="forumHeader">Forum Header</div>
<div id="content">Some content here</div>
我第一次向下滚动时,它正常工作并且动画#forumHeader top: 250px。但是当我再次向上滚动时,它可能需要几秒钟才能动画回到顶部:60px。有时它来回变化,有时它可能什么都不做。问题是什么?请帮忙..
我会使用 jQuery 添加和删除 class,然后使用 CSS 转换
$(document).ready(function(){
// EDIT - Move the selector outside of the scroll event as suggested
var header = $("#forumHeader");
$(window).scroll(function(){
if($(window).scrollTop() > 0) {
header.addClass('slide');
} else {
header.removeClass('slide');
}
});
});
#forumHeader{
top: 60px;
-webkit-transition: top 500ms ease-out ;
-moz-transition: top 500ms ease-out ;
-o-transition: top 500ms ease-out ;
transition: top 500ms ease-out ;
}
#forumHeader.slide{
top: 250px;
}
#content
{
height: 1000px;
background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="forumHeader">Forum Header</div>
<div id="content">Some content here</div>
希望对您有所帮助