[英]Trying to create a simple javascript gallery with a next and previous buttons to loop back to the beginning
[英]Trying to create a simple gallery slider
每當用戶點擊滑塊中的相應按鈕時,我試圖將左/右滑塊中的圖像集合的位置“分流”。 我有這個工作,但代碼有點大,重復,所以我一直試圖清除它,這是它的當前狀態:
$('#btnRight').click(function (e) {
e.preventDefault();
if (parseInt(6 + indexx) != 10) {
indexx++;
$('#first').attr('src', $('#second').attr('src'));
$('#second').attr('src', $('#third').attr('src'));
$('#third').attr('src', $('#fourth').attr('src'));
$('#fourth').attr('src', $('#fifth').attr('src'));
$('#fifth').attr('src', $('#sixth').attr('src'));
$('#sixth').attr('src', '/Content/Images/Gallery/Thumbs/' + parseInt(6 + indexx) + '.png');
}
});
您可以看到它是手動選擇每個元素並交換源屬性以將圖像移動到右側。
這是我一直致力於改進但不太有效的代碼:
$('#btnLeft').click(function (e) {
e.preventDefault();
$("#gallerySlider img").each(function (index) {
$(this).attr("src", $(this).prev().attr("src"));
});
});
這將獲取當前集合中的第一個圖像,並設置#gallerySlider
中所有圖像的來源,這是錯誤的。 但是,如果我在警報中放入相同的代碼,它會正確顯示圖像,並且它是前一個,例如輸出類似於:
/Content/Images/Design/Thumbs/10.png Previous Image: /Content/Images/Design/Thumbs/9.png
所以它正確選擇圖像並給我回正確的src
但為什么它將滑塊中所有圖像的來源設置為同一個? 當然它應該經歷所有這些並且:
$(this).prev().attr("src")
每個人會有所不同嗎?
任何人都可以看到我在這里出錯了嗎?
謝謝
如果你想象圖像1是“img1.jpg”而圖像2是“img2.jpg”等。
您放置的代碼將圖像2設置為“img1.jpg”,然后接下來將圖像3設置為圖像2的src,現在為“img1.jpg”,此圖像最終將成為所有這些圖像的src 。 那有意義嗎?
你有沒有在網上尋找jQuery類型的插件插件,因為那里有負載可以幫你完成工作嗎?
user1166905的答案聽起來很不錯。 一個解決方案是,如果你想向左移動,你可以從div中取出第一個元素,然后將它放回到div的末尾。 如果按向右鍵也是如此。 從列表中取出最后一個元素,將其從div中刪除,然后再將它放在圖庫div的開頭。
$('#btnLeft').click(function (e) {
e.preventDefault();
$('#gallerySlider').append($("#gallerySlider img").first());
});
$('#btnRight').click(function (e) {
e.preventDefault();
$('#gallerySlider').prepend($("#gallerySlider img").last());
});
我認為應該這樣做
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.