我的jQuery代码有问题。我有这个jQuery使元素在添加类时淡入淡出。动画到每个元素:
$(function(){
var $elems = $('.animateblock');
var winheight = $(window).height();
var fullheight = $(document).height();
$(window).scroll(function(){
animate_elems();
});
function animate_elems() {
wintop = $(window).scrollTop();
$elems.each(function(){
$elm = $(this);
if($elm.hasClass('animated')) { return true; }
topcoords = $elm.offset().top; // element's distance from top of page in pixels
if(wintop > (topcoords - (winheight*.75))) {
$elm.each(function(index) {
$(this).delay(300*index).addClass('animated');
});
}
});
}
});
如何让元素在延迟之后逐渐消失?
答案 0 :(得分:4)
可以通过使用fadeIn函数简单地完成,并为此函数提供所需的延迟。
var animated = $('.divs:first');
/* Need the first Element to FadeIn*/
/*I have stared the loop on document Ready*/
$(document).ready(function(){
fadeNext(animated);
});
function fadeNext(elem){
var eachDelay= 200;
/*check the necessary condition before you fadeIn the element*/
$(elem).fadeIn(eachDelay,function(){
$(elem).addClass('animated');
var nextElem = $(elem).next('.divs');
if(nextElem.length > 0){
fadeNext(nextElem);
}
});
}
*{
padding:0;
margin:0;
}
.divs{
width:cals(100% - 5px);
height:40px;
display:none;
background-color:#008800;
color:white;
padding:10px 10px 0 10px;
border-bottom:1px solid yellow;
text-align:center;
font-size:24px;
}
.animated{
background:red;
}
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<div class="divs">A</div>
<div class="divs">B</div>
<div class="divs">C</div>
<div class="divs">D</div>
<div class="divs">E</div>
<div class="divs">F</div>
<div class="divs">G</div>
<div class="divs">H</div>
<div class="divs">I</div>
答案 1 :(得分:1)
你可以用CSS做到这一点 - 没有必要使用jQuery。你可以用stagger.css
之类的东西来实现这一点http://digitalfio.github.io/Stagger.css/
将动画类应用于每个div,然后以下划线的形式向每个div添加一个计时类,后跟一个递增的数字 - 例如
<div class="animated slideIn _1"></div>
<div class="animated slideIn _2"></div>
<div class="animated slideIn _3"></div>
<div class="animated slideIn _4"></div>
所以你得到这样的东西:http://output.jsbin.com/cusuz/4
答案 2 :(得分:0)
通过使用可以从jquery index
函数获取的.each()
值,您可以像JS Fiddle
var eachDelay = 200,
animated = $('.animated');
animated.each(function(index) {
$(this).delay(index * eachDelay).animate({ 'opacity': 1 }, 1000);
});
&#13;
* {
padding: 0;
margin: 0;
}
.animated {
opacity: 0;
}
.divs {
width: cals(100% - 5px);
height: 40px;
display: block;
background-color: #008800;
color: white;
padding: 10px 10px 0 10px;
border-bottom: 1px solid yellow;
text-align: center;
font-size: 24px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="divs animated">A</div>
<div class="divs animated">B</div>
<div class="divs animated">C</div>
<div class="divs animated">D</div>
<div class="divs animated">E</div>
<div class="divs animated">F</div>
<div class="divs animated">G</div>
<div class="divs animated">H</div>
<div class="divs animated">I</div>
&#13;
<强>更新强>
如果你想在向下滚动时将它们淡入 - 即使你没有在你的OP中提及它,但看起来有点像 - 请检查JS Fiddle 2其中li
在向上滚动到窗口视图中时淡入