[英]How to create a fade-in and a fade-out loop with jQuery
So I am currently using a fade-in method on my program.所以我目前在我的程序上使用淡入方法。 However I want it to fade-in, fade-out and repeat the same process over and over again.但是我希望它淡入淡出并一遍又一遍地重复相同的过程。
What do I need to do that?我需要做什么?
$(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>
Depending on what visual effect you seek (the question is open to interpretation)...根据您寻求的视觉效果(这个问题可以解释)......
You can set up two mutualy-triggering custom events on the containing div.您可以在包含的 div 上设置两个相互触发的自定义事件。
To get the timing right, exploit jQuery's .promise()
, which returns a promise that will fulfill when the current animation(s) are complete.为了获得正确的时间,利用 jQuery 的.promise()
,它返回一个 promise ,它将在当前动画完成时完成。
To start the process, just trigger one or other of the custom events.要开始该过程,只需触发一个或其他自定义事件。
$(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.
});
untested未经测试
The process can undoubtedly be made more efficient, principally by working with the promise from only the final word, but the code will probably get messy.毫无疑问,这个过程可以变得更高效,主要是从最后一个字开始使用 promise,但代码可能会变得混乱。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.