使用 jQuery 为 iFrame 设置样式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4449477/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:17:19  来源:igfitidea点击:

Using jQuery to Style iFrame

jquerycssiframe

提问by ggutenberg

I've read about a dozen similar questions on here and tried everything I can think of, but I'm obviously doing something wrong because I just can't get it to work.

我在这里阅读了大约十几个类似的问题,并尝试了我能想到的一切,但我显然做错了什么,因为我无法让它发挥作用。

HTML:

HTML:

<iframe name="posts" id="posts" src="edit.php">

JS:

JS

$(document).ready(function() {
    $('iframe#posts').ready(function() {
        var frame = $('iframe#posts').contentDocument;
        console.log($('#adminmenu', frame));
        $('#adminmenu', frame).css('display', 'none !important');
    });
});

The console is outputting:

控制台输出:

[<ul id=?"adminmenu" style=?"display:? none !important;? ">?…?</ul>?]

which is the correct element. However the display:noneis never being applied in the browser. Also, I find it odd that the console is outputting with the inline style even though it's being set after the console.log()statement (not sure if that's related or not, but doesn't seem like it should be).

这是正确的元素。然而,display:none从未在浏览器中应用。此外,我觉得奇怪的是,即使它是在console.log()语句之后设置的,控制台也以内联样式输出(不确定这是否相关,但似乎不应该如此)。

Does anyone have any idea why this isn't working?

有谁知道为什么这不起作用?

I should also add that there is a <ul id="adminmenu">in the main document body as well, but I figured by providing the iframe context it should be targeting the iframe.

我还应该补充一点<ul id="adminmenu">,主文档正文中也有一个,但我认为通过提供 iframe 上下文,它应该针对 iframe。

回答by Nick Patterson

Have you tried using jQuery's contents()function instead of contentDocument?

您是否尝试过使用 jQuery 的contents()函数而不是contentDocument

$("iframe#posts").contents().find("#adminmenu").hide();

Updated: changed .css("display", "none !important")to simply .hide().

更新:更改.css("display", "none !important")为简单的.hide().

回答by dochoffiday

For an iframe, try the 'load' method instead of 'ready'. Also, use 'contents()' instead of 'contentDocument' to get the content of the iframe.

对于 iframe,请尝试使用 'load' 方法而不是 'ready'。此外,使用 'contents()' 而不是 'contentDocument' 来获取 iframe 的内容。

$(document).ready(function() {
    $('iframe#posts').load(function() {
        var frame = $('iframe#posts').contents();
        /* other code */
    });
});