【问题标题】:Changing the background of the image on click单击时更改图像的背景
【发布时间】: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


【解决方案1】:

为什么要使用 iframe ? 在 div 中使用 img 标签并更新 div 的背景颜色

<!DOCTYPE html>
<html>
<body>

<div id="myframe"><img src="http://img1.wikia.nocookie.net/__cb20110821045825/meme/images/3/3d/LOLGuy.png" />    </div>

<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 myframe = document.getElementById('myframe');
    myframe.style.backgroundColor = "red";
}
</script>

</body>
</html>

http://jsfiddle.net/TZXU3/1/

【讨论】:

  • 很好用!谢谢@安东尼。只是一个小问题,我使用 iframe 是因为我希望将图像包含在框架中。
【解决方案2】:
<iframe id="myframe" src="img-thing.png"></iframe>

png 文件是一个图像文件。它没有body 标签。所以它不会起作用。相反,请尝试将 HTML 链接(例如 something.html)放在 src 属性中。希望对您有所帮助。

如果要更改图像的背景颜色,请使用img 标签,而不是iframe。然后你可以直接访问img元素并改变它的背景颜色,比如document.getElementById("someimg").style.backgroundColor = "red";

【讨论】:

  • 谢谢@chris97ong。非常有价值的信息。
【解决方案3】:

如果你想在点击按钮时改变不同的颜色,那么试试这个,它可能对你有帮助

function changePic(picColor) {
   if(picName == "btnRed")
     {
        document.getElementById(mainPic).src = "mainPicRed.jpg"
      } 
   else if(picName == "btnbtnYellow ")
     {
       document.getElementById(mainPic).src = "mainPicYellow.jpg"
    } 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2017-03-07
    • 2013-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多