我试图通过逐字逐渐淡化的段落来制作文字。我搜索了很多,我发现了一些代码。代码运行良好,但我想在当前单词结束之前使下一个单词开始淡出。
因此,使用当前代码,单词逐个出现。现在,当当前单词大约有75%的不透明度时,我希望下一个单词开始出现,所以看起来会很闷。
我的代码:
var p = $(".sentences > p").hide();
(function oneParagraph(i) {
if (p.length <= i)
return;
var cur = p.eq(i),
words = cur.text().split(/\s/),
span = $("<span>"),
before = document.createTextNode("");
cur.empty().show().append(before, span);
(function oneWord(j) {
if (j < words.length) {
span.hide().text(words[j]).fadeIn(500, function() {
span.empty();
before.data += words[j]+" ";
oneWord(j+1);
});
} else {
span.remove();
before.data = words.join(" ");
if((p.length - 1) > i) {
setTimeout(function(){
p.hide();
}, 750);
}
setTimeout(function(){
oneParagraph(i+1);
}, 1000);
}
})(0);
})(0);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sentences">
<p>This is only a simple paragraph #1</p>
<p>This is only a simple paragraph #2</p>
<p>This is only a simple paragraph #3</p>
<p>This is only a simple paragraph #4</p>
<p>This is only a simple paragraph #5</p>
</div>
修改
我找到了一种如何创造我想要的效果的方法,但现在我还有另外一个问题。我不知道在显示句子后如何隐藏句子。
var P = $('.sentences > p');
P.hide().contents().each(function() {
var Words;
if (this.nodeType === 3) {
Words = '<span> ' + this.data.split(/\s+/).join(' </span><span> ') + ' </span>';
$(this).replaceWith(Words);
} else if (this.nodeType === 1) {
this.innerHTML = '<span> ' + this.innerHTML.split(/\s+/).join(' </span><span> ') + ' </span>';
}
});
P.find('span').hide().each(function() {
if( !$.trim(this.innerHTML) ) {
$(this).remove();
}
});
P.show().find('span').each(function(I) {
$(this).delay(200 * I).fadeIn(800);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="sentences">
<p>This is only a simple paragraph #1</p>
<p>This is only a simple paragraph #2</p>
<p>This is only a simple paragraph #3</p>
<p>This is only a simple paragraph #4</p>
<p>This is only a simple paragraph #5</p>
</div>
答案 0 :(得分:0)
您的代码正在等待来自fadeIn方法的回调,您可能尝试的不是等待它完成,只需创建一个75%fadeIn时间的计时器,并将其分配给下一步。
//而不是
span.hide().text(words[j]).fadeIn(500, function() {
span.empty();
before.data += words[j]+" ";
oneWord(j+1);
});
//喜欢
span.hide().text(words[j]).fadeIn(500);
window.setTimeout(300, function(){
span.empty();
before.data += words[j]+" ";
oneWord(j+1);
});