Setting Focus to an iFrame in IE

2019-06-22 09:18发布

问题:

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.

回答1:

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();
    }
}


回答2:

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);
});


回答3:

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.



回答4:

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();