我刚刚开始在工作中进一步提高我的网络开发技能,但遇到了一个小问题。
我有一个 iFrame (iframe.html),在此 iframe 中有一个样式为绿色方 block 的 div。 我想通过父级 (index.html) 中的按钮和 onClick 函数更改 iframe 外部 Div 的颜色。
我尝试了一些方法,例如调用普通函数(document.getElementById 等)。但没有什么真正起作用。 所以我想,jquery 可能有一些解决方案,我现在被困在这段代码中,但它不起作用。
有人可以帮忙吗?
PS:这不是跨源案例。我在同一目录中得到了两个 html 文件。
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/index.css">
<script src="jquery-1.12.2.min.js"></script>
<title>buttonframetest</title>
<script type="text/javascript">
function Clickit() {
$(document).ready(function(){
$('iframe').contents().find('background-color').css('backgroundColor', 'white');
});
}
</script>
</head>
<body>
<iframe id="iframe" src="iframe.html" width="500px;" height="500px">
<p>iFrame nicht darstellbar in deinem Browser</p>
</iframe>
<br>
<button type='button' onClick="Clickit();">Klick</button>
<button type="button" onclick="redy">CHANGE</button>
<br>
<div class="ChangeColor"></div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>
最佳答案
这可以通过 DOM iframe 对象的 contentDocument
属性来完成:
document.frames[0].contentDocument.getElementById('id here').style['background-color']=whatever;
或者,使用window.postMessage
:
// this is in parent
document.frames[0].postMessage('red', '*');
// this is in frame
window.onmessage = function(x) {
if (x.origin == 'http://www.example.com') document.getElementById('id here').style['background-color'] = x.data;
}
关于javascript - 从父级更改 iFrame 中 DIV 的 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37483841/