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

use*_*505 1 css iframe jquery

我尝试将外部页面加载到 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>
Run Code Online (Sandbox Code Playgroud)

Bhu*_*ake 5

src属性是否iframe具有与其父页面匹配的域、协议和端口?

如果不是并且iframe是外部的,那么您不能更改它的原因是同源策略

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

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

所以你的代码将是

<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>
Run Code Online (Sandbox Code Playgroud)