我正在尝试编写代码以将一个图像放置在整套元素上,但是允许单击以显示某些元素中的某些图像。
到目前为止,我的JS尚未更改任何元素。如果有人可以看看并给我建议,我将非常感激。
const cards = document.querySelectorAll(".card");
const flipAllCards = function() {
for (const card of cards) {
card.innerHTML = `<img src="img/cardback.jpeg" alt="">`;
}
};
flipAllCards();
function assignImages() {
for (const card of cards) {
const cardName = card.id;
const imageName = `${cardName}.jpeg`;
function flipCard(card) {
card.innerHTML = `<img src="img/${imageName}" alt="">`;
return card.innerHTML;
}
console.log(flipCard(card));
card.addEventListener('click', function() {
flipCard(card)
});
}
}
assignImages();
<div class="table">
<div class="card" id="agentbrown"><img src="img/agentbrown.jpeg" alt=""></div>
<div class="card" id="agentjones"><img src="img/agentjones.jpeg" alt=""></div>
<div class="card" id="agentsmith"><img src="img/agentsmith.jpeg" alt=""></div>
<div class="card" id="spoonboy"><img src="img/spoonboy.jpeg" alt=""></div>
<div class="card" id="switch"><img src="img/switch.jpeg" alt=""></div>
<div class="card" id="trinity"><img src="img/trinity.jpeg" alt=""></div>
</div>
答案 0 :(得分:1)
一种实现方法是让“ card”类在CSS中为所有卡片具有相同的“ background-image”,同时将div设为空。然后,当您需要翻转卡片时,只需在JS中添加具有相应ID的card.innerHTML图像