在iframe中动态插入/切换样式表(在我的域上托管的iframe源)

时间:2012-08-27 15:52:08

标签: javascript jquery iframe

我想知道是否有一个简单的解决方案来切换iframe页面上的样式表。基本上,这就是我的想法>

<iframe name="iframe" src="page on my domain.html"></iframe>

<form id="switcher">
  <input type="button" value="Switch to style 1" />
  <input type="button" value="Switch to style 2" />
  <input type="button" value="Switch to style 3" />
</form>

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

<iframe id="iframe" name="iframe" src="test.html"></iframe>
<form id="switcher">
  <input type="button" value="Switch to style 1" onclick="var a=document.getElementById('iframe').contentDocument.getElementsByTagName('link');a=a[0];a.href='path/to/some.css';" />
  <input type="button" value="Switch to style 2" />
  <input type="button" value="Switch to style 3" />
</form>

答案 1 :(得分:0)

假设安装了jQuery:

http://www.kelvinluck.com/2009/07/jquery-styleswitch-now-with-toggle/

好的,这真的要容易得多......我使用css zen garden来为这个测试设置样式页面:

表示您的HTML:

<iframe name="iframe" 
   id="iframetarget" 
   src="http://www.csszengarden.com/" 
   width=400 
   height=400>
</iframe>

<form id="switcher">
  <input type="button" id="v1" value="Switch to style 1" />
  <input type="button" id="v2" value="Switch to style 2" />
  <input type="button" id="v3" value="Switch to style 3" />
</form>​

对于你的jQuery:

$('#v1').click(function() {
    $('#iframetarget').prop({
        src: 'http://www.csszengarden.com/?cssfile=/213/213.css&amp;page=0'
    });
});
$('#v2').click(function() {
    $('#iframetarget').prop({
        src: 'http://www.csszengarden.com/?cssfile=/212/212.css&amp;page=0'
    });
});

$('#v3').click(function() {
    $('#iframetarget').prop({
        src: 'http://www.csszengarden.com/?cssfile=/211/211.css&amp;page=0'
    });
});​

这是用小提琴测试的,它有效:

http://jsfiddle.net/sablefoste/DbYPp/1/

相关问题