![](/img/trans.png)
[英]Why are the images are not cycling through, when using this JavaScript?
[英]Why are these images not cycling through while using JQuery?
我正在尝试浏览3张彼此重叠的图像。 我正在使用的jQuery对图像没有任何影响,并且我看不到问题出在哪里。 我真的很想帮忙! 干杯!!
HTML:
<div id="cycler">
<img class="active" src="images/dubcity4.jpg" alt="my image"/>
<img src="images/dubcity2.jpg" alt="my image"/>
<img src="images/dubcity3.jpg" alt="my image"/>
</div>
CSS:
#cycler{position:relative;}
#cycler img{position:absolute;z-index:1}
#cycler img.active{z-index:3}
JavaScript:
function cycleImages(){
var $active = $('#cycler.active');
var $next = ($active.next().length > 0) ? $active.next() : $('#cycler img:first');
$next.css('z-index', 2);
$active.fadeOut(1500, function(){
$active.css('z-index',1).show().removeClass('active');
$next.css('z-index',3).addClass('active');
});
}
$(document).ready(function(){
setInterval('cycleImages()',2000);
})
更改此:
var $active = $('#cycler.active');
对此:
var $active = $('#cycler .active');
在您的代码中,您尝试查找id =“ cycler” AND class =“ active”的元素,这是错误的
还尝试将函数传递给setInterval而不是字符串
setInterval(cycleImages,2000);
参见jSfiddle http://jsfiddle.net/ygV3z/
可以肯定的是,这是错误的: $('#cycler.active');
您应该有$('#cycler .active');
因为.active
为后代#cycler
。 您的选择器正在寻找一个ID = cycler
的元素,该元素也已分配了active
类。
您在CSS选择器中输入了错误。 只需通过更改它来修复它:
var $active = $('#cycler.active');
分为以下内容:
var $active = $('#cycler .active');
JQuery具有each
方法,可以帮助您循环访问DOM元素:
$("#cycler img").each(function(key, obj) {
// fetch the arguments passed
var args = arguments;
// get a jquery accessible form of each object
var obj = $(obj);
// do stuff
});
您可以匹配名称或类,甚至可以匹配属性(如果它们相同)。 我敢肯定,技术娴熟的人会告诉您1是否比另一个更快,但是属性的符号应为$("#cycler [data-pick='true']")
以匹配#cycler
中的每个图像定义如下: <img src="..." data-pick="true" />
。
希望这可以帮助。
就像这里的每个人都说的那样,您需要在CSS选择器之间留一个空格,以表示您想要后代。 另外,您需要使用:first-child
,而不是:first
。
同样,您不能将字符串传递给setTimeout()
。 此外, setTimeout()
期望在其第一个参数中使用实际的回调函数 , 而不是该函数返回的值 。 您正在执行的操作与此非常相似:
function looper() {
$(this).hide();
}
$("img").each("looper()");
那没有任何意义,是吗?
现在,固定代码:
function cycleImages(){
var $active = $('#cycler .active');
var $next = ($active.next().length > 0) ? $active.next() : $('#cycler img:first-child');
$next.css('z-index', 2);
$active.fadeOut(1500, function(){
$active.css('z-index',1).show().removeClass('active');
$next.css('z-index',3).addClass('active');
});
}
$(document).ready(function(){
setInterval(cycleImages,2000);
})
这是小提琴: http : //jsfiddle.net/NobleMushtak/L4D7r/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.