how to change background-color of external page lo

2019-01-29 06:18发布

I try to load external page into iframe and change background-color of that page
here is the code (it is not working - it change color of parent page not iframe page):

<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>

3条回答
Luminary・发光体
2楼-- · 2019-01-29 06:39

You can't; it's a security restriction not to be able to modify the internals of iframes coming from different domains such as filehippo.com (think about how dangerous modifying other sites' login pages, for instance, can be).

On the other hand, note that your method wouldn't work even if the iframe's contents were coming from the same domain. See this question for the right way to do it.

查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-01-29 07:01

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

If no and the iframe is external, then reason you can not change it is because of Same Origin Policy.

If yes, then you can add <body> to the iframe and use this

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

So your code will be

<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>
查看更多
Fickle 薄情
4楼-- · 2019-01-29 07:04

Pure Javascript to archive this override color on body

Javascript

var x = document.getElementById("myframe");
var y = x.contentWindow.document;
y.body.style.backgroundColor = "red";

View live W3Schools

查看更多
登录 后发表回答