jquery - 如何更改加载到 iframe 的外部页面的背景颜色

标签 jquery css iframe

我尝试将外部页面加载到 iframe 中并更改该页面的背景颜色
这是代码(它不起作用 - 它改变父页面而不是 iframe 页面的颜色):

<style type="text/css">
iframe {
    background-color: #F00;
}
</style>

<iframe src="http://www.filehippo.com/" height="100%" width="100%">
</iframe>


<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $('body').css('background-color', '#F00');
});
</script>

最佳答案

Does the src attribute of the iframe have matching domain, protocol and port to its parent page?

如果否,则 iframe是外部的,那么 您无法更改它的原因是 Same Origin Policy .

如果是,那么您可以添加 <body>到 iframe 并使用它

$(document).ready(function(){
    $('iframe').contents().find('body').css('backgroundColor', 'Your Color');
});

所以你的代码将是

<html>
<body>
<style type="text/css">
iframe {
    background-color: #F00;
}
</style>
<iframe src="http://www.filehippo.com/" height="100%" width="100%"></iframe>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
    $('iframe').contents().find('body').css('backgroundColor', 'white');
});
</script>
</body>
</html>

关于jquery - 如何更改加载到 iframe 的外部页面的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14913649/

相关文章:

javascript - 通过 keydown 事件防止箭头键滚动

jquery - 使用 html 类而不是 del 元素来覆盖文本

javascript - ng-click 与 Bootstrap 评级

css - jQueryUI 选项卡出现在所有其他元素之上

css - 如何在右侧设置宽度适合内容 - 动态内容宽度

javascript - 在默认 PDF 查看器的 iframe 中禁用/隐藏下载按钮

javascript - 使用数据发布 jQuery 移动更改页面

jquery - VS2015中jQuery安装在哪里?

css - 列文本位置不匹配;延长列线?

html - Iframe 是我唯一的选择吗?