在IE11中无法使用JavaScript聚焦输入



我无法让IE11在插入到DOM后聚焦输入元素。元素在聚焦后不会接收文本输入,但其占位符文本不再可见。元素是由React创建的,我通过React的refs对象在componentDidMount中访问它:

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

我尝试使用setTimeout添加短延迟:

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

我还尝试添加"1"tabIndex到输入。

如果它有帮助,这里是渲染的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>

是否有一些技巧,让焦点在IE11工作,我不知道?

当css属性-ms-user-select: none应用于输入时,问题集中在IE11中。通过改变:

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

*:not(input) {
  -ms-user-select: none;
}
我能够解决这个问题。以下是再现该问题的代码:http://codepen.io/anon/pen/yNrJZz

如https://stackoverflow.com/a/31971940所述,当设置了css属性-ms-user-select: none时,在IE11中运行element.focus()无效。变通方法可以是

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

不能在IE中使用:https://codepen.io/macjohnny-zh/details/WPXWvy
(代码:https://codepen.io/macjohnny-zh/pen/WPXWvy)

也适用于IE: https://codepen.io/macjohnny-zh/details/LqOvbZ
(代码:https://codepen.io/macjohnny-zh/pen/LqOvbZ)

注意:这也会发生,例如

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

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

我不认为你的问题是来自focus()函数,我认为它来自选择器。

为了证明这一点,我打开了IE11,并尝试使用以下命令将SO搜索输入集中在页面的右上角:

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

所以,只要打开IE控制台(F12)并输入,它应该集中搜索输入。如果是这样,那么问题来自于选择器,而不是你可能认为的输入。

它适用于我的IE 11.0.9600.17905

最新更新