Question:
Tell me the best way: you need to display the first picture by clicking on the first button
, and display the second picture by clicking on the second button
. When one image is displayed, another is hidden.
Code example:
<div class="box">
<button class="b1">Push please</button>
<img class="watermelon" src="https://cdn3.iconfinder.com/data/icons/food-set-3/91/Food_C246-256.png" alt="">
</div>
<div class="box">
<button class="b2">Push please</button>
<img class="apple" src="https://cdn3.iconfinder.com/data/icons/fruits-8/512/apple-256.png" alt="">
</div>
div {
display: inline-block;
width: 400px;
text-align: center;
}
button {
font-size: 30px;
}
.apple {
display: none;
}
Answer:
В JS
noob, кажется не слишком хорошим решением, но всё же вот:
var first = document.getElementById('btn1');
var second = document.getElementById('btn2');
var watermelon = document.getElementsByClassName('watermelon')[0];
var apple = document.getElementsByClassName('apple')[0];
first.onclick = function() {
apple.classList.add("off");
watermelon.classList.remove("off");
watermelon.classList.add("on");
}
second.onclick = function() {
watermelon.classList.add("off");
apple.classList.remove("off");
apple.classList.add("on");
}
.box {
display: flex;
justify-content: center;
align-items: center;
text-align: center;
}
button {
font-size: 20px;
height: 50px;
}
.on {
display: block;
}
.off {
display: none;
}
<div class="box">
<button class="b1" id="btn1">Watermelon</button>
<button class="b2" id="btn2">Apple</button>
</div>
<div class="box">
<img class="watermelon" src="https://cdn3.iconfinder.com/data/icons/food-set-3/91/Food_C246-256.png" alt="">
<img class="apple off" src="https://cdn3.iconfinder.com/data/icons/fruits-8/512/apple-256.png" alt="">
</div>