简体   繁体   English

动态设置Src时更改iframe样式

[英]Change Iframe Style When the Src is Set Dynamically

In my site I have this iframe 在我的网站上,我有这个iframe

<iframe id='iFrameName1' width='1000' height='500'></iframe>

The src tag is dynamically defined with javascript. src标签是使用javascript动态定义的。 In addition, I want to dynamically change the style of the iframe (it is in the same domain). 此外,我想动态更改iframe的样式(它位于同一域中)。

<script> function urlChange() {      
var iframe1 = document.getElementById('iFrameName1'); 
iframe1.src = 'mypage.html';
var cssLink = document.createElement("link"); 
cssLink.href = "iframe.css";  
cssLink.rel = "stylesheet";  
cssLink.type = "text/css"; 
iframe1.contentDocument.getElementsByTagName('head')[0].appendChild(cssLink); 
}  
</script>

The problem is: as the src is defined dynamically, I think the "iframe1.contentDocument" is not found. 问题是:由于src是动态定义的,因此我认为未找到“ iframe1.contentDocument”。

How to solve this problem? 如何解决这个问题呢? I want to define the src and to change the iframe style dynamically. 我想定义src并动态更改iframe样式。

Thanks in advance. 提前致谢。

EDIT: 编辑:

You can handle onload event of your iframe like this: 您可以像这样处理iframe的onload事件:

iframe1.onload = function(){ 
 ....
}

Your code could go like this: 您的代码可能如下所示:

function urlChange() {      
    var iframe1 = document.getElementById('iFrameName1'); 
    iframe1.src = 'mypage.html';

    iframe1.onload = function(){
       var cssLink = document.createElement("link") 
       cssLink.href = "iframe.css"; 
       cssLink.rel = "stylesheet"; 
       cssLink.type = "text/css"; 
       var y = (iframe1.contentWindow || iframe1.contentDocument);
       if (y.document)y = y.document;
       y.getElementsByTagName('head')[0].appendChild(cssLink);  
    }
}

DEMO : 演示
http://swift-exploder-php-36-103575.apne1.nitrousbox.com/test/iframe/1.html http://swift-exploder-php-36-103575.apne1.nitrousbox.com/test/iframe/1.html

The document of contentWindow is here: http://www.w3schools.com/jsref/prop_frame_contentwindow.asp contentWindow的文档在这里: http : //www.w3schools.com/jsref/prop_frame_contentwindow.asp

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM