如何使jquery-ui自动完成跳出iframe?

3

是否可能使自动完成 (jQueryUI) 的建议从一个iframe中出来,具有“select”元素的相同行为?我举一个例子:

http://jsbin.com/ehidef/1

1个回答

2
事实上,这是可以做到的,尽管一些样式是必须的。jQueryUI 接受一个元素来附加选项,并且您可以将父窗口作为该元素传递。以下是一个示例:
主窗口:
<html>
    <head></head>
    <body>
        <iframe src="iframe.html"></iframe>
    </body>
</html>

iframe.html

<html>
    <head>
        <!-- include jQuery and jQuery UI and the like -->
        <script type="text/javascript">
            jQuery(function($){
                // This will take parent frame if in iframe, own body elsehow
                var el=top.document.body 

                // Instructs jQuery UI to show things on that previous element
                $('input').autocomplete({appendTo:el}); 
            });
        </script>
    </head>
    <body>
        <input type="text"/>
    </body>
</html>

整个示例中没有与解释重点无关的内容,因此它不起作用。根据需要进行调整并添加一些修饰。
至于我之前提到的样式,您将需要为元素指定位置和样式,因为1)相对于输入位置的位置在父窗口上是无关紧要的,2)父窗口不需要加载jqueryui样式表,尽管您可以使用类似的技术从iframe内部动态加载它们。
重要提示:
只有当父窗口和子窗口位于同一个域中时,才能正常工作[参见:SOP]。
更新:
在完成相同事情后,我想出了这个解决方案来设置样式和位置:
var files=[ // UI styles to be loaded on top frame
        "css/ui-lightness/jquery-ui-1.10.3.custom.css",
        "css/ui-lightness/custom.css"
]

// Create link tag and append to top frame head
for (var a in files) {
    var style=$("<link/>", {
        rel: "stylesheet",
        type: "text/css",
        href: files[a]
    });

    $(top.document).find('head').append(style);
}

// As it turns out i had many iframes, so this will get the right one
var parentIframe=$(el).find('iframe').filter(function(){
    return window.frameElement==this
});

$('input').each(function(){ // Cicle inputs to use with ui autocomplete
    // set position to left + input offset  2 is a fix for borders on input
    var pos= "left+"+($(this).offset().left+2)+
    // and to top + input position + height to have it on the bottom
             " top+"+($(this).offset().top+$(this).outerHeight()+1);

    // Autocomplete 
    $(this).autocomplete({
        appendTo:top.document.body, // put it on top window's body
        position:{
            at: pos,        // at calculated position
            of:parentIframe // from parent iframe
        }
    })

});

再次提醒,可能会有空缺,请随意填写相关代码。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接