gpt4 book ai didi

jQuery 在 div 内一次循环 p 标签的 .fadeIn 和 .fadeOut

转载 作者:行者123 更新时间:2023-12-01 00:36:43 25 4
gpt4 key购买 nike

下面的代码成功淡入一个感言 6 秒,等待 3 秒,然后淡出并转到下一个感言。一旦到达第三个推荐,它就会跳回第一个。这正是我想要的,但在我的实际网站上,我有超过三个推荐,并且将来可能会添加更多。我不想每次添加新的推荐时都必须返回并添加新功能。我尝试了一段时间使用“this”和 .next() 让它工作但失败了。我希望有人可以通过循环它并使其移动到容器内的下一个 p 标签来提高效率,而不必每次都调用新函数。感谢任何帮助,谢谢。

注意:我知道有类似的问题,但没有一个是完全相同的,而且答案也低于标准。

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<style>
#tml-container p { display: none; }
</style>
</head>
<body>

<div id="tml-container">
<p id="one">Testimonial 1</p>
<p id="two">Testimonial 2</p>
<p id="three">Testimonial 3</p>
</div>

<script>
$(document).ready(function() {
function doFade() {
$("#one").fadeIn(6000,function() {
$("#one").fadeOut(6000).delay(3000);
setTimeout(fadeTwo,6000);
});
}

function fadeTwo() {
$("#two").fadeIn(6000,function() {
$("#two").fadeOut(6000).delay(3000);
setTimeout(fadeThree,6000);
});
}

function fadeThree() {
$("#three").fadeIn(4000,function() {
$("#three").fadeOut(6000).delay(3000);
setTimeout(doFade,6000);
});
}
doFade();
});
</script>

</body>
</html>

最佳答案

这是一个非常简单的解决方案:

function fade($ele) {
$ele.fadeIn(6000).delay(3000).fadeOut(6000, function() {
var $next = $(this).next('p');
// if there is a following `p` element, it is faded in
// otherwise start from the beginning by taking
// the parent's first child
fade($next.length > 0 ? $next : $(this).parent().children().first());
});
};

fade($('#tml-container > p').first());

DEMO

<小时/>

可重复使用的插件版本:

它不是迭代某个元素的子元素,而是迭代选定的元素。

(function($) {
var default_config = {
fadeIn: 3000,
stay: 3000,
fadeOut: 3000
};

function fade(index, $elements, config) {
$elements.eq(index)
.fadeIn(config.fadeIn)
.delay(config.stay)
.fadeOut(config.fadeOut, function() {
fade((index + 1) % $elements.length, $elements, config);
});
}

$.fn.fadeLoop = function(config) {
fade(0, this, $.extend({}, default_config, config));
return this;
};

}(jQuery));

可用作:

$('#tml-container > p').fadeLoop({fadeIn: 6000, stay: 3000, fadeOut: 6000});

DEMO

关于jQuery 在 div 内一次循环 p 标签的 .fadeIn 和 .fadeOut,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8616395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com