如何使用javascript从父级向iFrame添加样式表

How do I add a stylesheet to an iFrame from the parent, using javascript?

本文关键字:iFrame 添加 样式 何使用 javascript      更新时间:2023-09-26

我的JSFiddle:http://jsfiddle.net/gCRuk/1/

HTML:

My replays on SC-Replay.com:<br>
<iframe frameborder="0" name="frame" id="frame1" src="http://www.sc-replay.com/embedPlayer/21368-TheLindyHop.html" style="left: 0pt; position: relative; top: 0pt; width: 980px; height: 500px; border: 0px solid #00214E;" n="" vspace="0" marginheight="0" marginwidth="0" hspace="0" allowtransparency="true"></iframe>

Javascript:

var ss = document.createElement("link");
ss.type = "text/css";
ss.rel = "stylesheet";
ss.href = "http://www.lprestonsegoiii.com/WordPress/wp-content/themes/arjuna-x/style.css";
var iframe;
if(document.frames)
    iframe = document.frames["frame"];
else
    iframe = window.frames["frame"];
if(document.all)
    iframe.document.createStyleSheet(ss.href);
else
    iframe.document.getElementsByTagName("head")[0].appendChild(ss);

我遵循以下指南:http://www.geekdaily.net/2007/09/19/javascript-adding-a-stylesheet-to-an-iframe/

我真的不确定这里发生了什么/出了什么问题。

一般来说,由于JavaScript的同源策略,您不能跨域执行此操作。

如果iframe页面、容器页面和CSS文件都来自同一个域,这是可能的,这是GeekDaily教程中假设的(但不幸的是没有提到!)。