3 回答

TA貢獻1829條經(jīng)驗 獲得超4個贊
使用 jQuery 你會這樣做。
請給你的圖像元素一個類。否則,您也可以切換所有圖像標(biāo)簽。
$('.prev_btn, .next_btn').on('click', function(e) {
$('.img').toggle();
});
展開片段如果你想切換所有圖像,那么只需:
$('img').toggle();

TA貢獻1802條經(jīng)驗 獲得超5個贊
$('.prev_btn, .next_btn').on('click', function(e) {
var this$ = $(e.currentTarget), // grab the currently clicked button element
parent$ = this$.parents('#pro').first(), // grab the parent of the button that has the id #pro
contextBasedImgs$ = parent$.find('img'); // grab all the images in the parent div with id #pro
contextBasedImgs$.each(function(ignore, el) {
var currEl$ = $(el),
newURI = currEl$.attr('onmouseout');
currEl$.attr('src', newURI);
});
});

TA貢獻2012條經(jīng)驗 獲得超12個贊
首先,將您的圖像移動到圖像本身屬性上的數(shù)組中data-
- 這為您提供了不同的圖像集和任意數(shù)量的圖像 - 而不是僅僅在兩個之間切換,您不需要下一個和上一個按鈕,所以暗示是你想要兩個以上的圖像。
<img?data-images='["https://www.w3schools.com/html/img_chania.jpg","https://www.w3schools.com/html/pic_trulli.jpg"]'?...
接下來,使用 js/jquery 事件處理程序而不是 HTMLonclick=
只會讓您更好地控制和分離 html/代碼等
$(".prev_btn").click(function()?{
在此處理程序中,我們使用您的父包裝器找到相關(guān)圖像。在這里我給了包裝器 aclass
而不是 anid
這樣你就可以擁有多個包裝器而不需要不同的 ID 并且更容易在 css 中設(shè)置樣式(而不是.closest("div")
)
$(this).closest(".wrapper").find("img").first()
并且點擊事件處理程序調(diào)用帶有方向的通用方法(而不是重復(fù)所有相同的代碼)
這在每個圖像上存儲當(dāng)前索引,因此不需要額外的變量來“記住”
img.data("index",?new_index);
然后是從圖像中讀取數(shù)組,根據(jù)方向更改索引并更新圖像的情況。
我不得不對按鈕的 CSS 進行一些調(diào)整(僅用于演示),第二張圖片包含第三張圖片網(wǎng)址,以顯示它不僅可以切換
$(".prev_btn").click(function() {
? ? changeImage($(this).closest(".wrapper").find("img").first(), -1)
});
$(".next_btn").click(function() {
? ? changeImage($(this).closest(".wrapper").find("img").first(), 1)
});
function changeImage(img, direction)
{
? ? var images = img.data("images");
? ? var idx = img.data("index");
? ??
? ? idx += direction;
? ? if (idx >= images.length) idx = 0;
? ? if (idx < 0) idx = images.length - 1;
? ??
? ? img
? ? ? .data("index", idx)
? ? ? .attr("src", images[idx]);
}
.wrapper {
? position:relative;
}
.prev_btn, .next_btn {
? position:absolute;
? left: 0;
? top: 0px;
? bottom: 0;
? width: 30px;
? height: 255px;
? z-index: 2;
? border-style: dotted;
}
.next_btn {
? left: 170px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
? <img width="206" height="260"?
? ? ? ?src="https://www.w3schools.com/html/pic_trulli.jpg"?
? ? ? ?data-images='["https://www.w3schools.com/html/img_chania.jpg","https://www.w3schools.com/html/pic_trulli.jpg"]'
? ? ? ?data-index="1">
? <div class="prev_btn"></div>
? <div class="next_btn"></div>
</div>
<div class="wrapper">
? <img width="206" height="260"?
? ? ? ?src="https://www.w3schools.com/html/img_chania.jpg"?
? ? ? ?data-images='["https://www.w3schools.com/html/img_chania.jpg","https://www.w3schools.com/html/pic_trulli.jpg", "https://www.w3schools.com/html/img_girl.jpg"]'
? ? ? ?data-index="0">
? <div class="prev_btn"></div>
? <div class="next_btn"></div>
</div>
添加回答
舉報