Setting Focus to an iFrame in IE

2019-06-22 08:34发布

There is a tree menu in my application and on click of the menu items, it loads a url in a iFrame. I like to set the focus in an element of the page loaded in the iFrame.

I'm using this code, and it works perfectly in all the browsers except IE:

var myIFrame = $("#iframeName");
myIFrame.focus();
myIFrame.contents().find('#inputName').focus();

I have tried all different options like using setTimeout, but no chance.

After the page loads, when I hit the tab key, it goes to the second input, which means it's been on the first input, but it doesn't show the cursor!

I am using ExtJS and the ManagedIFrame plugin.

Any help is appreciated.

4条回答
对你真心纯属浪费
2楼-- · 2019-06-22 09:08

You need to call the focus() method of the iframe's window object, not the iframe element. I'm no expert in either jQuery or ExtJS, so my example below uses neither.

function focusIframe(iframeEl) {
    if (iframeEl.contentWindow) {
        iframeEl.contentWindow.focus();
    } else if (iframeEl.contentDocument && iframeEl.contentDocument.documentElement) {
        // For old versions of Safari
        iframeEl.contentDocument.documentElement.focus();
    }
}
查看更多
闹够了就滚
3楼-- · 2019-06-22 09:08

Difficult to troubleshoot without a working example, but you might try hiding and showing the input as well, to force IE to redraw the element.

Something like:

var myIFrame = $("#iframeName");
myIFrame.focus();
myIFrame.contents().find('#inputName').hide();
var x = 1;
myIFrame.contents().find('#inputName').show().focus();

This might jolt IE into displaying the cursor.

查看更多
Animai°情兽
4楼-- · 2019-06-22 09:10

I could get IE to focus an input field in an iframe with:

iframe.focus();
var input = iframe...
input.focus();
iframe.contentWindow.document.body.focus();
input.focus();
查看更多
姐就是有狂的资本
5楼-- · 2019-06-22 09:15

Is the iFrame visible onload, or shown later? The elements are created in different order which is the basis of the setTimeout approach. Did you try a high value wait time on a set timeout?

Try something like at least a half second to test...IE tends to do things in a different order, so a high timeout may be needed to get it not to fire until render/paint finishes:

$(function(){
  setTimeout(function() {
    var myIFrame = $("#iframeName");
    myIFrame.focus();
    myIFrame.contents().find('#inputName').focus();
    }, 500);
});
查看更多
登录 后发表回答