如果特定的if / else语句为true,如何生成特定的图像?
我一直在尝试,但是src只会使图像停留在页面上,并且当if语句为false时不会消失。
if (B == "k k"){
//I want my image to appear through this if statement
}else {
//and a separate image to appear if this "else" is true
}
答案 0 :(得分:0)
您可以通过在图像上设置display: none;
(以下示例片段)来有条件地显示或隐藏图像:
function toggleImage() {
var img = document.querySelector('img');
if (img.style.display === 'block') {
img.style.display = 'none';
} else {
img.style.display = 'block';
}
}
button {
display: block;
margin: 20px 0;
}
<button onclick="toggleImage()">toggle image</button>
<img src="https://source.unsplash.com/random/200x200" style="display: block;" />
答案 1 :(得分:0)
为您的图片添加ID
<img id="your-image-id" src="" alt="" >
您可以在if语句上设置src
var img = document.getElementById("your-image-id")
if (B == "k k"){
img.src ="linkto your image"
}else {
img.src ="linkto your another image"
}