[英]How to create a fade-in and a fade-out loop with jQuery
所以我目前在我的程序上使用淡入方法。 但是我希望它淡入淡出並一遍又一遍地重復相同的過程。
我需要做什么?
$(document).ready(function() { var $el = $(".intro"); var text = $el.text(); var words = text.split(" "); var html = ""; for (var i = 0; i < words.length; i++) { html += "<span>" + words[i] + " </span>"; } $el.html(html).children().hide().each(function(i) { $(this).delay(i * 1500).fadeIn(1700) }); });
<,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1:0"> <title>Document</title> </head> <body> <script src="https.//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="test.js"></script> <div class="intro">PREDICT SIMULATE OPTIMIZE</div> </body> </html>
根據您尋求的視覺效果(這個問題可以解釋)......
您可以在包含的 div 上設置兩個相互觸發的自定義事件。
為了獲得正確的時間,利用 jQuery 的.promise()
,它返回一個 promise ,它將在當前動畫完成時完成。
要開始該過程,只需觸發一個或其他自定義事件。
$(document).ready(function() {
var $el = $('.intro');
var $words = $el.html($el.text().split(' ').map(word => `<span>${word} </span>`).join('')).children().hide();
$el.on('fadeIn', function() { // custom event
$.when(...$words.map(function(i, word) => $(word).delay(i * 1500).fadeIn(1700).promise()))
.then(function() {
$el.trigger('fadeOut'); // trigger fadeOut when fadeIn is complete
});
}).on('fadeOut', function() { // custom event
$.when(...$words.map(function(i, word) => $(word).delay(i * 1500).fadeOut(1700).promise()))
.then(function() {
$el.trigger('fadeIn'); // trigger fadeIn when fadeOut is complete
});
}).trigger('fadeIn'); // start a never ending fadeIn/fadeOut cycle.
});
未經測試
毫無疑問,這個過程可以變得更高效,主要是從最后一個字開始使用 promise,但代碼可能會變得混亂。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.