我真的希望这不是一个愚蠢的问题......在过去的几个小时里我一直在用头撞墙试图解决它。
这本质上是 How to create a <style> tag with Javascript 的后续问题, Stack Overflow 上的其他地方。 Tom 和 Michael 描述的技术在 IE、Firefox 和 Opera 中工作得很好,在 Chrome 和 Safari 中也几乎工作。问题是,在 Chrome 和 Safari 中,没有为样式表创建“cssRules”属性!其他浏览器创建一个“cssRules”属性(好吧,IE 创建一个“规则”属性,但你已经知道了)。
谁能解释如何为 iframe 创建样式表,以便在 Chrome 和 Safari 中为我提供“cssRules”属性?
我的目的是将样式表添加到我在网页中创建的 iframe,因为它似乎没有附带样式表。后来,我希望从附件文档的样式表中复制一些样式到 iframe 的样式表中,但我还没有做到。如果有人知道在我解决上述问题后这样做的任何注意事项,我将提前感激不尽。
最佳答案
我已经在 Firefox 3.6、Chromium 8、Opera 11 (ubuntu 10.10) 中测试过
temp.html:
<style>
body { background-color: blue; }
</style>
<body>
Hello
</body>
index.html:
<html>
<head>
<script>
function test(){
// your new <style> tag
var stl = document.createElement("style");
// its content
stl.innerHTML = "body { background-color: red}";
// getting iframe
var myIframe = document.getElementById("myiframe");
// apply new CSS to iframe
myIframe.contentWindow.document.
getElementsByTagName('head')[0].appendChild(stl);
}
</script>
</head>
<body>
<iframe id="myiframe" src="temp.html"></iframe>
<button onclick="test()">
</body>
</html>
当我点击按钮时,iframe 中的背景变为红色。
附言对不起,如果它是重复的。我现在才打开您帖子中指向另一个主题的链接
关于html - 在 JavaScript 中创建 <style> 标签,然后访问 cssRules,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4903175/