英文:
Trying to create an invisible button to change an image
问题
我正在尝试在页面的一个小部分上放置一个不可见按钮以更改背景图片。
但是,按钮没有更改为指定的图像。
var image = document.getElementById('myImage');
image.addEventListener('click', function(){
changeImage();
});
function changeImage(){
image.src = 'img/lab.svg';
}
<img src="img/vault.svg" alt="">
<button id="myImage"> </button>
英文:
I am trying to have an invisible button on a small part of the page to change the background image.
But, the button doesn't change the image to the one specified.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
var image = document.getElementById('myImage');
image.addEventListener('click', function(){
changeImage();
});
function changeImage(){
image.src = 'img/lab.svg';
}
<!-- language: lang-html -->
<img src="img/vault.svg" alt="">
<button id="myImage"> </button>
<!-- end snippet -->
答案1
得分: 2
你似乎将按钮引用(变量 image
)与 <img>
元素混淆了。
请确保使用明智的名称(对于您的变量和 ID)以避免混淆。
你将按钮引用保存在变量 image
中,并尝试更改其 src
属性。
相反,你应该分配给图片的 src
属性:
const button = document.getElementById('image-button');
const image = document.getElementById('image');
button.addEventListener('click', function(){
changeImage();
});
function changeImage(){
image.src = 'img/lab.svg';
}
<img id="image" src="img/vault.svg" alt="">
<button id="image-button"> </button>
注意:我更改了变量名和元素ID。
英文:
You seem to confuse your button reference (variable image
) with the <img>
element.
Make sure you use sensible names (for your variables and IDs) to avoid confusions.
You save the button reference in the variable image
, and try to change its src
property.
Instead, you should assign to the image's src
attribute:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const button = document.getElementById('image-button');
const image = document.getElementById('image');
button.addEventListener('click', function(){
changeImage();
});
function changeImage(){
image.src = 'img/lab.svg';
}
<!-- language: lang-html -->
<img id="image" src="img/vault.svg" alt="">
<button id="image-button"> </button>
<!-- end snippet -->
Note: I changed the variable names and element IDs.
答案2
得分: 0
你可以使用image.onload
和image.onerror
来了解发生了什么。
var image = document.getElementById('myImage');
image.addEventListener('click', function(){
changeImage();
});
image.onerror = function(e) { console.log('加载失败', e); }
image.onload= function(e) { console.log('加载成功', e); }
function changeImage(){
image.src = 'img/lab.svg';
}
英文:
You could use image.onload
and image.onerror
to understand what's happening.
var image = document.getElementById('myImage');
image.addEventListener('click', function(){
changeImage();
});
image.onerror = function(e) { console.log('Loading failed', e); }
image.onload= function(e) { console.log('Loading successful', e); }
function changeImage(){
image.src = 'img/lab.svg';
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论