如何使用 JavaScript 从 iFrame 最内层的正文标签内部设置最外层的正文标签样式?
<html>
<head>
</head>
<body>
<div id="ad_tag" style="width: 1px; height: 1px;">
<div id="ad_container" style="border: 0pt none;">
<iframe id="ad_iframe" title="title" name="name" scrolling="no" marginwidth="0" marginheight="0" style="border: 0px none; vertical-align: bottom;" srcdoc="" width="1" height="1" frameborder="0">
<html>
<head>
</head>
<body topmargin="0" leftmargin="0" marginwidth="0" marginheight="0">
<script>
parent.document.body.style.background = "url('https://news.nationalgeographic.com/content/dam/news/photos/000/676/67655.jpg') no-repeat top center fixed #ffffff";
</script>
</body>
</html>
</iframe>
</div>
</div>
<div id="content">
</div>
</body>
</html>
- 在此特定情况下:
- 不允许直接编辑属性或样式,现有是预设的。
- 只能编辑最内层主体的子元素。
- 目标是使用Google DFP提供背景图像。
最好的方法是使用来自框架的发布消息,父(站点(将通过侦听器执行。所以你的 iframe 应该包含一些代码,例如:
<script>
window.parent.postMessage({
'func': 'changeBackground',
'message': ''
}, "*");
</script>
您的父级(站点(应包含如下侦听器:
<script type="text/javascript">
if (window.addEventListener) {
window.addEventListener("message", onMessage, false);
}
else if (window.attachEvent) {
window.attachEvent("onmessage", onMessage, false);
}
function onMessage(event) {
var data = event.data;
if (typeof(window[data.func]) == "function") {
window[data.func].call(null, data.message);
}
}
function changeBackground(message) {
$('div#backgroundwrapper').css({
'background-image': 'url("https:/example.com/example.jpg")',
$('div#backgroundwrapper').click();
var win = window.open( '%%CLICK_URL_ESC%%%%DEST_URL%%', '_blank');
win.focus();
});
}
</script>
在我的示例中,它将图像文件作为背景放在具有 ID 背景包装器的div 上。我的例子使用jQuery来更改CSS并添加一个点击标签,但它也可以在没有它的情况下制作。