jQuery fadeout在循环时不工作
问题描述:
我试图执行这个脚本,它会将数组中的单词附加到<p>
标记上,当完成时它将用另一个短语替换整个句子,然后重新开始。jQuery fadeout在循环时不工作
我得到的问题是,当从第二个短语过渡到应用淡出效果并返回添加淡出效果的第一个短语时。如果没有淡出效果,它会按预期工作,但包含它时不会循环回到开始。
任何人都可以帮助我找出淡出效果为什么会弄乱代码,以及如何使它与淡出效果一起工作。
这里是断码:
var index = 0;
Start();
function Start() { // DOM ready
var str = ["First", ", Second", ", Third", ", Fourth."];
var spans = '<span>' + str.join('</span><span>') + '</span>';
$(spans).hide().appendTo('#motto').each(function(i) {
$(this).delay(2000 * i).fadeIn('slow', 'swing', function() {
if (index == 3) {
setTimeout(Restart, 2000);
} else {
index++;
}
});
});
}
function Restart() {
$('#motto').fadeIn('slow', 'swing', function() {
var div = $("<p id='motto'>Second Phrase.</p>").hide();
$('#motto').replaceWith(div);
$('#motto').fadeIn("slow", 'swing', function() {
setTimeout(function() {
var reset = $("<p id='motto'></p>").hide();
$('#motto').replaceWith(reset).fadeOut('slow', 'swing', function() {
index = 0;
Start();
});
}, 3000);
});
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="motto"></p>
这里是没有淡出效果代码:
var index = 0;
Start();
function Start() { // DOM ready
var str = ["We Listen", ", We Plan", ", We Advise", ", We Deploy."];
var spans = '<span>' + str.join('</span><span>') + '</span>';
$(spans).hide().appendTo('#motto').each(function(i) {
$(this).delay(2000 * i).fadeIn('slow', 'swing', function() {
if (index == 3) {
setTimeout(Restart, 2000);
} else {
index++;
}
});
});
}
function Restart() {
$('#motto').fadeIn('slow', 'swing', function() {
var secondPhrase = $("<p id='motto'>Everything you need for a successful implementation.</p>").hide();
$('#motto').replaceWith(secondPhrase);
$('#motto').fadeIn("slow", 'swing', function() {
setTimeout(function() {
var reset = $("<p id='motto'></p>");
$('#motto').replaceWith(reset);
index = 0;
Start();
}, 3000);
});
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="motto"></p>
答
这是因为在破碎的示例中,您已将.hide()
添加到reset
声明的末尾。如果您删除该方法调用,则代码循环正常。
工作液:
var index = 0;
Start();
function Start() { // DOM ready
var str = ["First", ", Second", ", Third", ", Fourth."];
var spans = '<span>' + str.join('</span><span>') + '</span>';
$(spans).hide().appendTo('#motto').each(function(i) {
$(this).delay(2000 * i).fadeIn('slow', 'swing', function() {
if (index == 3) {
setTimeout(Restart, 2000);
} else {
index++;
}
});
});
}
function Restart() {
$('#motto').fadeIn('slow', 'swing', function() {
var div = $("<p id='motto'>Second Phrase.</p>").hide();
$('#motto').replaceWith(div);
$('#motto').fadeIn("slow", 'swing', function() {
setTimeout(function() {
var reset = $("<p id='motto'></p>");
$('#motto').replaceWith(reset).fadeOut('slow', 'swing', function() {
index = 0;
Start();
});
}, 3000);
});
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="motto"></p>