Using jQuery to Style iFrame

2019-03-25 07:32发布

问题:

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:

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

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:none is 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).

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.

回答1:

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

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

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



回答2:

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

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