我尝试制作动画,以便当用户打开我的网站时动画开始播放。
它应该首先显示第一个h1
,然后在1s之后它应该消失并显示第二个h1
并且在另一个1s之后,第二个h1
消失然后它显示第三个h1
,依此类推。我找到了jquery .delay()
,但我无法弄清楚如何在这里使用它。我已经有了一些代码。
如果有人可以帮助我,我会很高兴。
<div class="intro">
<div class="intro-text">
<h1 class="intro-text-1">Hi</h1>
<h1 class="intro-text-2">My</h1>
<h1 class="intro-text-3">Name</h1>
<h1 class="intro-text-4">Is</h1>
</div>
.intro-text h1 {
text-align: center;
color: #fff;
left: 0;
right: 0;
display: none;
animation: fadein 2s;
}
@keyframes fadein {
from {opacity: 0;}
to {opacity: 1;}
}
$(document).ready(function(){
$(".intro-text-1").css("display", "block");
// $(".intro-text-1").delay(2000).css("display", "none");
});
但是,当我尝试.delay()时它没有用。
您可以使用超时来实现此功能。
$(document).ready(function(){
var $introText = $(".intro-text-1");
$introText.css("display", "block");
setTimeout(function(){
$introText.css("display", "none");
}, 2000);
});
看起来你在同时使用CSS和jQuery时会感到困惑。
我建议您严格使用CSS动画或使用jQuery的方法(但不是两者)执行此动画。
.intro-text.css h1 {
opacity: 0;
animation-name: fadein;
animation-duration: 2s;
}
@keyframes fadein {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
.css .intro-text-1 {
animation-delay: 0s;
}
.css .intro-text-2 {
animation-delay: 1s;
}
.css .intro-text-3 {
animation-delay: 2s;
}
.css .intro-text-4 {
animation-delay: 3s;
}
h1 {
margin: 0;
}
<div class="intro-text css">
<h1 class="intro-text-1">Hi</h1>
<h1 class="intro-text-2">My</h1>
<h1 class="intro-text-3">Name</h1>
<h1 class="intro-text-4">Is</h1>
</div>
$(function() {
$(".intro-text.js h1").each(function(index) {
$(this).css('opacity', 0);
$(this).delay(1000 * index).animate({
opacity: 1
}, 2000, function() {
$(this).css('opacity', 0)
});
});
})
h1 {
margin: 0;
}
<script src="https://code.jquery.com/jquery-1.12.3.js" integrity="sha256-1XMpEtA4eKXNNpXcJ1pmMPs8JV+nwLdEqwiJeCQEkyc=" crossorigin="anonymous"></script>
<div class="intro-text js">
<h1 class="intro-text-1">Hi</h1>
<h1 class="intro-text-2">My</h1>
<h1 class="intro-text-3">Name</h1>
<h1 class="intro-text-4">Is</h1>
</div>
我想通过利用setInterval
来增加@Taplar的答案,让函数循环通过.intro-text
的孩子自己:
$(document).ready(function(){
var intros = $(".intro-text").children();
var index = 0;
setInterval(function(){
if(index < intros.length){
intros.hide();
$(intros[index]).show();
index++;
}
}, 1000)
});