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

IT技术 javascript internet-explorer reactjs react-jsx
2021-05-05 16:32:53

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

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

我尝试使用setTimeout以下方法添加短暂延迟

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

我也曾尝试加入tabIndex"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 中专注于工作,而我不知道?

3个回答

当 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 中所述设置element.focus()css 属性后,在 IE11 中运行无效-ms-user-select: none解决方法可以是

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