尝试使用JavaScript将css样式添加到iframe
在Wordpress上尝试此功能: 在我的尝试使用JavaScript将css样式添加到iframe,javascript,html,jquery,css,iframe,Javascript,Html,Jquery,Css,Iframe,在Wordpress上尝试此功能: 在我的iframe中有一个\u2p3a类,我想将其宽度更改为\u2p3a{width:100%!important;} 使用CSS无法访问该类,因此我尝试使用JavaScript: 我的JS代码: function hello() { let myiFrame = document.getElementById("iframe-css"); let doc = myiFrame.contentDocument; doc.b
iframe
中有一个\u2p3a
类,我想将其宽度更改为\u2p3a{width:100%!important;}
使用CSS无法访问该类,因此我尝试使用JavaScript:
我的JS代码:
function hello() {
let myiFrame = document.getElementById("iframe-css");
let doc = myiFrame.contentDocument;
doc.body.innerHTML = doc.body.innerHTML + '<style>._2p3a{width: 100% !important;}</style>';
}
下划线代码:
.body.innerHTML = doc.body.innerHTML + '<style>._2p3a{width: 100% !important;}</style>';
.body.innerHTML=doc.body.innerHTML+'。_2p3a{宽度:100%!重要;}';
尝试:
(所有示例均出现错误“无工作”)
我在iframe上使用onload=“hello(this)”
运行此函数
任何关于如何编辑该类以使其宽度达到100%的其他建议?请尝试下面的代码。。。我希望你得到结果:
let myiFrame = document.getElementById("iframe-css").contentWindow;
let doc = myiFrame.document;
doc.body.innerHTML = doc.body.innerHTML + '<style>._2p3a{width: 100% !important;}</style>';
让myiFrame=document.getElementById(“iframe css”).contentWindow;
让doc=myiFrame.document;
doc.body.innerHTML=doc.body.innerHTML+'。_2p3a{宽度:100%!重要;}';
添加
元素不是最好的方法。但是,即使是这样,也应该尽量避免通过innerHTML
添加元素。最好使用Document.createElement
(Document
是Document
的实例)和Element.appendChild
(所有元素都是元素
类的实例)
最好的方法是直接修改类中元素的样式
函数hello(){
让myiFrame=document.getElementById(“iframe css”);
让doc=myiFrame.contentDocument??myiFrame.contentWindow?.document??新文档();
让elements=doc.getElementsByClassName(“2p3a”);
for(设i=0;ionload
属性有时在iFrame上不起作用。您可能必须像这样使用DOM:
document.getElementById(“iframe css”).onload=hello;
另一方面,在JavaScript中,通常应该使用2到4个空格的缩进,但选择了3个。决定使用不同的插件,因为使用facebook iframe会带来一些麻烦。有了这个新插件,一切都很好
感谢所有努力回答的人,我感谢您的帮助。从这个“”land_page.js?ver=1.0:9未捕获类型错误中得到以下错误:“@RandomCoder确保您的id正确无误。如果是,请确保加载iframe后运行
hello
。请记住,只有在加载DOM后才能访问iframe的onload。也许这段代码可以解决您的问题:window.onload=()=>{document.getElementById(“iframe css”).onload=hello;}
如果这不能解决您的问题,请尝试以下操作:window.onload=hello
如果这仍然不能解决您的问题,那么我不知道除了尝试jQuery的$(document).ready
方法之外还有什么可以告诉您的。出现以下错误““land_page.js?ver=1.0:7 Uncaught DOMException:阻止带有原点的帧”访问跨原点帧。在htmliframelement.onload()”的hello()处我认为,因为它是一个facebook的iframe,DOM正在阻止我的javascript代码requestyes它的阻止是因为它不在您的源代码中,但是如果主题(iframe和parrent)都在同一个域或地址中,它就可以正常工作。
let myiFrame = document.getElementById("iframe-css").contentWindow;
let doc = myiFrame.document;
doc.body.innerHTML = doc.body.innerHTML + '<style>._2p3a{width: 100% !important;}</style>';