Unable to focus an input using JavaScript in IE11

2019-02-17 11:16发布

问题:

I'm unable to get IE11 to focus an input element after it is inserted into the DOM. The element won't receive text input after being focused, but its placeholder text is no longer visible. The element is created by React, and I'm accessing it through React's refs object in componentDidMount:

componentDidMount() {
    this.refs.input.getDOMNode().focus();
}

I have tried adding a short delay using setTimeout:

componentDidMount() {
    setTimeout(() => this.refs.input.getDOMNode().focus(), 10);
}

I have also tried adding a tabIndex of "1" to the input.

In case it's helpful, here is the rendered JSX:

<div style={style}>
    <div style={labelStyle}>Enter a name to begin.</div>

    <form onSubmit={this.submit} style={formStyle}>
        <input 
             tabIndex="1" 
             ref="input" 
             value={this.state.username} 
             onChange={this.updateUsername}
             placeholder="New User Name" 
             style={inputStyle}
        />
        <button {...this.getBrowserStateEvents()} style={this.buildStyles(buttonStyle)}>Create</button>
    </form>
</div>

Is there some trick to getting focus to work in IE11 that I'm unaware of?

回答1:

The issue was focusing in IE11 is broken when the css property -ms-user-select: none is applied to the input. So by changing:

* {
  -ms-user-select: none;
}

into

*:not(input) {
  -ms-user-select: none;
}

I was able to solve the problem. Here is a codepen for reproducing the issue: http://codepen.io/anon/pen/yNrJZz



回答2:

I don't think that your issue is coming from the focus() function, I think it's coming from the selector.

To prove it I just opened my IE11 and tried to focus the SO search input on the top right of the page using the following command:

document.getElementById('search')[0].focus()

So, just open your IE console (F12) and type that, it should focus the search input. If so, then the issue is coming from the selector which isn't an input as you may think.

It works on my IE 11.0.9600.17905



回答3:

As stated in https://stackoverflow.com/a/31971940, running element.focus() has no effect in IE11 when the css property -ms-user-select: none is set. A workaround can be

element.style['-ms-user-select'] = 'text';
element.focus()
element.style['-ms-user-select'] = '';

Does not work in IE: https://codepen.io/macjohnny-zh/details/WPXWvy
(Code: https://codepen.io/macjohnny-zh/pen/WPXWvy)

Works in IE, too: https://codepen.io/macjohnny-zh/details/LqOvbZ
(Code: https://codepen.io/macjohnny-zh/pen/LqOvbZ)

Note: this also happens e.g. for

:-ms-input-placeholder {
  -ms-user-select: none;
}

See https://github.com/angular/material2/issues/15093