![](/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.