我有一个jQuery函数,可以在div中输入/输出图像。但是当函数到达最后一个图像时,它就会被停止。任何在循环中得到它的方法,以便在最后一个映像的末尾,它将从第一个图像重新开始。这是代码
HTML:
<div id="homeimg">
<img src="image1.jpg" />
<img src="image2.jpg" />
<img src="image3.jpg" />
<img src="image4.jpg" />
</div>
jQuery:
$(document).ready(function(){
$('#homeimg img:first-child').addClass('activeimg');
setInterval('cycleMe()', 4000);
});
function cycleMe() {
$('.activeimg').next().css('z-index', 10);
$('.activeimg').next().fadeIn(1500);
$('.activeimg').fadeOut(1500, function(){
$(this).next().fadeIn(0);
$(this).next().addClass('activeimg');
$(this).css('z-index', 5).removeClass('activeimg');
});
}
有什么可能吗?
发布于 2014-02-06 18:17:50
您还可以通过简单的数组操作来完成这一任务:
$(document).ready(function () {
$('#homeimg img:first-child').addClass('activeimg');
setInterval(cycleMe, 4000);
// get an array of your images
var arrImgs = $('#homeimg img');
function cycleMe() {
var currImg = arrImgs[0];
var nextImg = arrImgs[1];
// You can do this with simple array splicing and pushing
$(nextImg).css('z-index', 10);
$(nextImg).fadeIn(1500);
$(currImg).fadeOut(1500, function () {
$(nextImg).fadeIn(0);
$(this).css('z-index', 5);
// remove the first item from the array
arrImgs.splice(0,1);
// add it to the end of the array
arrImgs.push(currImg);
});
}
});
jsFiddle:http://jsfiddle.net/mori57/4FbVD/
考虑到伊森的一些评论,我也尝试过这样做:
http://jsfiddle.net/mori57/4FbVD/2/
$(document).ready(function () {
$('#homeimg img:first-child').addClass('activeimg');
setInterval(cycleMe, 4000);
// get an array of your images
var arrImgs = $('#homeimg img');
function cycleMe() {
var currImg = $(arrImgs[0]);
var nextImg = $(arrImgs[1]);
// You can do this with simple array splicing and pushing
nextImg.fadeIn(1500);
currImg.fadeOut(1500, function () {
currImg.removeClass('activeimg');
nextImg.fadeIn(0).addClass('activeimg');
// remove the first item from the array
arrImgs.splice(0,1);
// add it to the end of the array
arrImgs.push(currImg);
});
}
});
在我之前的尝试中,我不得不请求DOM,以获得css更改和fadeIn .效率低下。缓存jQuery对象,/然后/执行操作,和sans-z索引,就像Ethan的方法一样。我仍然不希望对无限循环中的每个元素请求DOM。如果我能找到解决这个问题的方法,我也会把它发出去。
发布于 2014-02-06 18:06:14
首先,将函数作为字符串传入,这是一个no-no。我认为您的代码过于复杂了,而且您可以利用一些jQuery效率。
首先,我不认为有必要修改图像的z索引:褪色应该处理所有这些。其次,您可以链接jQuery调用(参见下面fadeIn
和addClass
是如何链接的)。最后,每次执行$('.activeimage')
时,jQuery都必须再次扫描DOM,这是效率低下的。最好只做一次并缓存答案(每当我存储一个jQuery对象时,我都会按照约定以一个美元符号开头,所以我总是知道我在处理一个jQuery包装的对象)。
以下是我重写的方法:
$(document).ready(function(){
$('#homeimg img:first-child').addClass('activeimg');
setInterval(cycleMe, 4000);
});
function cycleMe() {
var $active = $('#homeimg .activeimg');
var $next = $active.next('img');
if(!$next.length) $next = $('#homeimg img:first-child');
$active.fadeOut(1500, function(){
$(this).removeClass('activeimg');
$next.fadeIn().addClass('activeimg');
});
}
工作小提琴:http://jsfiddle.net/6MHDn/
https://stackoverflow.com/questions/21610527
复制相似问题