我最终想做的是最初隐藏一个框和一个图像,然后根据其他函数的结果取消隐藏框(通过给它一个背景颜色)和图像,并根据更改图像在被调用的函数上。
下面的代码有两个问题:
- 首先是在执行时会出现框,但图像会出现 不是。
- 第二次调用任一函数时(它不抛出 脚本的其余部分(这是一个计算器,所以第一次调用时出错) 它会发生多次)然后我得到一个错误,好像图像没有 不再存在:
"JavaScript runtime error: Unable to set property 'src' of undefined or null reference"
脚本:
function one(input) {
document.getElementById("result").style.background = "lightgray";
document.getElementById("result").style.color = "green";
document.getElementById("icon").src = "tick.png";
document.getElementById("icon").style.visibility = "visible";
}
function two(input) {
document.getElementById("result").style.background = "lightgray";
document.getElementById("result").style.color = "red";
document.getElementById("icon").src = 'cross.png';
document.getElementById("icon").style.visibility = "visible";
}
HTML:
<div id="result">
<img src="tick.png" id="icon" style="visibility:hidden">
</div>
和 CSS(虽然需要怀疑):
#result {
width: 820px;
height: 450px;
border-radius: 20px;
padding-top:25px;
padding-bottom: 25px;
color: green;
font-size:40pt;
text-align: center;
margin-top: 100px;
margin-right: 150px;
margin-left:420px;
}
#result img{
margin-top: 85px;
width:220px;
height: 190px;
}
最佳答案
Barmar 让我开始思考,谢谢!
在调用函数时查看 DOM 后发现脚本的另一部分使用 .innerText 替换了 HTML 中的代码(仍然不明白为什么会这样做)所以第一次调用我的标签是走了,因此试图调用空引用。将 放在它自己的 div 中解决了这个问题。
还在 css 中添加了一个设置为 absolute 的位置属性,并通过将图像重新显示在 View 中解决了该问题。
感谢大佬们的帮助,感激不尽! :)
关于javascript - 隐藏/更改/添加图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14300395/