使用JS间隔更改HTML的图像

时间:2013-09-03 14:42:34

标签: javascript jquery setinterval

我有一个代码,我需要做一个简单的操作:我的div中有28个图像,我需要每41ms更改一次。

我有HTML:

<div class="full_slider">
<img id="bgs_49" style="visibility: visible; display: block; opacity: 1;" src="images/background/10_00049.jpg" class="full_slider_child" alt="bg" />
<img id="bgs_50" src="images/background/10_00050.jpg" class="full_slider_child" alt="bg" />
<img id="bgs_51" src="images/background/10_00051.jpg" class="full_slider_child" alt="bg" />
<img id="bgs_52" src="images/background/10_00052.jpg" class="full_slider_child" alt="bg" />
<img id="bgs_53" src="images/background/10_00053.jpg" class="full_slider_child" alt="bg" />
<img id="bgs_54" src="images/background/10_00054.jpg" class="full_slider_child" alt="bg" />
<img id="bgs_55" src="images/background/10_00055.jpg" class="full_slider_child" alt="bg" />
<img id="bgs_56" src="images/background/10_00056.jpg" class="full_slider_child" alt="bg" />
<img id="bgs_57" src="images/background/10_00057.jpg" class="full_slider_child" alt="bg" />
<img id="bgs_58" src="images/background/10_00058.jpg" class="full_slider_child" alt="bg" />
<img id="bgs_59" src="images/background/10_00059.jpg" class="full_slider_child" alt="bg" />
<img id="bgs_60" src="images/background/10_00060.jpg" class="full_slider_child" alt="bg" />
<img id="bgs_61" src="images/background/10_00061.jpg" class="full_slider_child" alt="bg" />
<img id="bgs_62" src="images/background/10_00062.jpg" class="full_slider_child" alt="bg" />

我有JS:

var bgs = ['49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '61', '60', '59', '58', '57', '56', '55', '54', '53', '52', '51', '50', '49']
var pos = 1;


setInterval(function() {
pos = (pos+1) % bgs.length;
pos_early = (pos-1) % bgs.length;

slider_next = $("#bgs_" + pos);
slider_prev = $("#bgs_" + pos_early);

slider_prev.css({
   'visibility' : 'hidden',
   'display'    : 'none',
   'opacity'    : 0 
});

slider_next.css({
   'visibility' : 'visible',
   'display'    : 'block',
   'opacity'    : 1 
});
}, 41);

我需要做的是,每41ms previuos图像应该可见:none,display:none,opacity:0,下一个图像应该可见:visible,display:block和opacity:1。我该怎么做它?

BTW:我的代码无效

2 个答案:

答案 0 :(得分:2)

试试这个

var cntMax = $('.full_slider').find('img').length;
var cnt = 0;
setInterval(function(){
   $('.full_slider img:eq('+cnt+')').show().siblings().hide();
   cnt==cntMax? cnt=0:cnt++;
},41);

答案 1 :(得分:0)

根据我上面的评论,另一种方法是切换课程,以便将所有css保留在样式表中,以便分离关注点

<强> JS

setInterval(function () {
    $(".full_slider img").eq(0).removeClass('show').next('img').addClass('show').end().appendTo(".full_slider");
}, 41);

<强> CSS

.full_slider_child.show {
    visibility: visible; 
    display: block; 
    opacity: 1;
}