【发布时间】:2014-07-30 16:37:36
【问题描述】:
我有一张图片需要在点击时更改背景。我使用以下 javascript 和 html 来做这件事。为简单起见,我首先首选红色背景,参考图像是透明背景。
代码是:
<!DOCTYPE html>
<html>
<body>
<iframe id="myframe" src="img-thing.png"></iframe>
<p>Click the button to change the background color of the picture contained in the iframe.</p>
<p id="demo"></p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction()
{
var x = document.getElementById("myframe");
var y = (x.contentWindow || x.contentDocument);
y.body.style.backgroundColor="red";
}
</script>
</body>
</html>
我知道在这里使用 iframe 可能有问题,所以我尝试了:
<div id="myframe"><img src="img-thing.png"></div>
而不是 iframe。如果我从 iframe 标记中删除 src 字段,它可以正常工作。但是当我插入图像并单击立即尝试时,它不起作用。请帮忙。
【问题讨论】:
-
请忽略我不好的英语。
-
iframe标签没有img src属性。它具有src属性,但没有img src -
对不起,我试过了,但还是没有结果。
-
这行我看不懂:
if (y.document)y = y.document;y.document是什么? -
即使我也不确定。我从w3schools.com/jsref/…
标签: javascript html css iframe web