Javascript 如何在闪烁元素中连续显示图像?
我已经为此挣扎了很长一段时间了 我有一个div,我想让它每X秒出现一次,每Y秒消失一次。 没问题,我有这样的想法:Javascript 如何在闪烁元素中连续显示图像?,javascript,jquery,Javascript,Jquery,我已经为此挣扎了很长一段时间了 我有一个div,我想让它每X秒出现一次,每Y秒消失一次。 没问题,我有这样的想法: <div id="container" class="forced-ad"> <div class="dummy"></div> <div class="img-container centerer"> <img class="centered" src="http://placekitten.c
<div id="container" class="forced-ad">
<div class="dummy"></div>
<div class="img-container centerer">
<img class="centered" src="http://placekitten.com/200/200" alt="forced-ad">
<img class="centered" src="http://placekitten.com/201/200" alt="forced-ad">
<img class="centered" src="http://placekitten.com/200/201" alt="forced-ad">
</div>
</div>
jQuery:
function makeContainerAppear(displayTime, interval) {
setInterval( function() {
$("#container").show("slow","swing");
setTimeout( function() {
$("#container").hide("slow","swing");
}
, displayTime * 1000);
, interval * 1000);
}
$(document).ready(function() {
$("#container").hide();
makeContainerAppear(5,10);
});
Html:
<div id="container" class="forced-ad">
<div class="dummy"></div>
<div class="container-img centerer">
<img class="centered" src="http://placekitten.com/200/200">
</div>
</div>
及
但是我找不到一种方法来增加:eq(i)
第5行中的i
变量,并使其与#container
div中的项数(img
)循环
在这种情况下,使图像以以下方式显示:1>2>3>1>2>3>
谢谢你的建议 您需要在显示下一个img之前增加var,以便它可以位于$((“img:eq(i)”).show()之后;或者在setTimeout(函数(){ 或者可以像这样使用.delay()
//declare the adIndex variable and save the container and imgs elements
var adIndex=0,$container=$("#container"),$ads=$(".img-container").children("img");
function makeContainerAppear() {
//hide all $ads and only show the one in adIndex
$ads.hide().eq(adIndex%3).show();
$container.hide().delay(10000).show("slow","swing")
.delay(5000).hide("slow","swing",function(){
adIndex++;
//call the same function when container is hidden
makeContainerAppear();
});
}
makeContainerAppear();
太好了!这两个解决方案效果很好,但我将选择第二个,因为第一个解决方案在短时间内似乎有点不稳定:图像不会定期出现。请注意,我将I%3替换为I%3+1以使3个图像交替。我%3工作了,但交替的是2个图像和一个空白。
var i=0;//declare the i variable
function makeContainerAppear(displayTime, interval) {
setInterval( function() {
$("#container").show("slow","swing");
$("img").hide();
//$("img:eq("+i+")") or $("img").eq(i)
//i++ can be here
$("img:eq("+i+")").show();
setTimeout( function() {
//check if it is less than 3 return to 0 or use i%3 inside eq
i++;
$("#container").hide("slow","swing");
}
, displayTime * 1000);
}, interval * 1000);
}
//declare the adIndex variable and save the container and imgs elements
var adIndex=0,$container=$("#container"),$ads=$(".img-container").children("img");
function makeContainerAppear() {
//hide all $ads and only show the one in adIndex
$ads.hide().eq(adIndex%3).show();
$container.hide().delay(10000).show("slow","swing")
.delay(5000).hide("slow","swing",function(){
adIndex++;
//call the same function when container is hidden
makeContainerAppear();
});
}
makeContainerAppear();