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

Unable to focus an input using JavaScript in IE11

插入 DOM 后,我无法让 IE11 聚焦输入元素。该元素在获得焦点后不会接收文本输入,但其占位符文本不再可见。该元素由 React 创建,我通过 componentDidMount:

中的 React 的 refs 对象访问它
componentDidMount() {
    this.refs.input.getDOMNode().focus();
}

我尝试使用 setTimeout:

添加一个短暂的延迟
componentDidMount() {
    setTimeout(() => this.refs.input.getDOMNode().focus(), 10);
}

我也试过在输入中添加 tabIndex of "1"

如果有帮助,这里是呈现的 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 中集中注意力的技巧?

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

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

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

因此,只需打开您的 IE 控制台 (F12) 并键入它,它应该会聚焦搜索输入。如果是这样,那么问题出在选择器上,它不是您想象的输入。

它适用于我的 IE 11.0.9600.17905

当 css 属性 -ms-user-select: none 应用于输入时,IE11 中的焦点问题被打破。所以通过改变:

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

进入

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

我能够解决问题。这是用于重现该问题的代码笔: http://codepen.io/anon/pen/yNrJZz

所述,当设置 css 属性 -ms-user-select: none 时,运行 element.focus() 在 IE11 中无效。 解决方法可以是

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