【问题标题】:Hide / Change / Add an image隐藏/更改/添加图像
【发布时间】:2012-12-27 08:20:22
【问题描述】:

我最终想要做的是最初隐藏一个框和一个图像,然后根据其他功能的结果,然后取消隐藏框(通过给它一个背景颜色)和图像以及更改图像取决于在被调用的函数上。

下面的代码有两个问题:

  • 首先是在执行时会出现框,但图像会出现 不是。
  • 第二次调用任一函数时(它抛出 no 第一次调用时出错)由脚本的其余部分(它是一个计算器所以 它会发生多次)然后我得到一个错误,好像图像没有 不再存在:

"JavaScript 运行时错误:无法设置未定义的属性 'src' 或空引用”

JScript:

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;
    }

【问题讨论】:

  • 当你得到那个错误时,你还能在 DOM 检查器中看到 icon 元素吗?
  • jsfiddle 链接:jsfiddle.net/h5XF2
  • 我无法复制您的错误。请看这个小提琴:jsfiddle.net/jDVjP/1
  • Oomlaut,你的小提琴就像 OP 在 Firefox 中为我描述的那样。我确实看到图像短暂闪烁,然后消失了。随后的点击没有显示图像。更正:我没有意识到最终的图像是全黑的。我不确定为什么隐藏元素上的图像源不同。

标签: javascript html css image src


【解决方案1】:

Barmar 让我思考,非常感谢!

在调用函数时查看了 DOM 后,发现使用 .innerText 的脚本的另一部分正在替换 HTML 中的代码(仍然不明白为什么会这样做)所以第一次调用我的标签是走了,因此试图调用空引用。将 div 放在自己的 div 中解决了这个问题。

还在 css 中添加了一个位置属性设置为绝对,并通过将图像重新显示到视图中来解决该问题。

感谢各位大侠的帮助,不胜感激! :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多