html:
<div class="vaultcontainer">
<img src="img/vault.svg" alt="" id="image">
</div>
<button id="image-button">click </button>
<button id="image-button2">click </button>
js:
const button = document.getElementById('image-button');
const image = document.getElementById('image');
button.addEventListener('click', function() {
changeImage();
});
function changeImage() {
image.src = 'img/vault2.svg';
}
使用類別:
<button class="js-changeImage">click </button>
<button class="js-changeImage">click </button>
然后,在JS中使用querySelectorAll()和。返回的節點列表上的forEach():
const buttons = document.querySelectorAll('js-changeImage');
buttons.forEach(btn => btn.addEventListener('click', changeImage));
如果需要為按鈕指定不同的圖像,請使用data-*屬性:
<img src="img/vault.svg" alt="" id="image">
<button data-image="img/cat.svg">click </button>
<button data-image="img/dog.svg">click </button>
const image = document.querySelector('#image');
const buttons = document.querySelectorAll('[data-image]');
buttons.forEach(btn => btn.addEventListener('click', () => {
changeImage(btn.dataset.image);
});
function changeImage(src) {
image.src = src;
}
上一篇vue 表單構建器