jQuery css附加到iframe一瞬间

时间:2014-02-22 11:12:34

标签: javascript jquery iframe

所以我创建了一个用户有多个链接的页面,当用户点击链接时,iFrame会更改src并向用户显示内容。

现在我得到了这个适用于iframe中每个页面的css文件,而不是将css文件应用到其他每个页面(可能很多)我想我将我的css附加到iframe中。

但只有当你离开页面时它才有效,你可以看到短暂的css。

这是我的代码:

$(document).ready(function() { 
    //The iframe
    var frameContent = $("#frameContent");    

    $(".SideMenuWrapper a").each(function() {

        //Gets the href for each link so we dont have to write a click event for all the links
        var href = $(this).attr("href");

        $(this).click(function(e) {         
            e.preventDefault();          

            //Applying the css to the iframe
            var head = frameContent.contents().find("head");
            head.append($("<link/>", {rel : "stylesheet", href : "../lib/css/gui.css", type: "text/css"}));

            frameContent.attr('src', href);          
        });
    });  
});

我试过在frameContent.attr('src', href);下移动头部但是这似乎也不起作用。

1 个答案:

答案 0 :(得分:2)

在我看来,你应该使用iframe的onload事件:

$(document).ready(function () {
    //The iframe
    var frameContent = $("#frameContent");
    $('.SideMenuWrapper a').click(function (e) {
        e.preventDefault();
        //Gets the href for each link so we dont have to write a click event for all the links
        var href = $(this).attr("href");
        //Applying the css to the iframe

        frameContent.on('load', function () {
            var head = $(this).contents().find("head");
            head.append($("<link/>", {
                rel: "stylesheet",
                href: "../lib/css/gui.css",
                type: "text/css"
            }));
        }).attr('src', href);
    });
});