[英]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
"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中工作而我不知道?
當css屬性-ms-user-select: none
應用於輸入時,問題集中在IE11中。 所以通過改變:
* {
-ms-user-select: none;
}
成
*:not(input) {
-ms-user-select: none;
}
我能夠解決問題。 這是一個用於復制問題的codepen: http ://codepen.io/anon/pen/yNrJZz
我不認為你的問題來自focus()函數,我認為它來自選擇器。
為了證明這一點,我剛剛打開IE11並嘗試使用以下命令將SO搜索輸入集中在頁面的右上角:
document.getElementById('search')[0].focus()
所以,只需打開你的IE控制台(F12)並鍵入它,它應該集中搜索輸入。 如果是這樣,那么問題就來自選擇器,它不是您想象的輸入。
它適用於我的IE 11.0.9600.17905
如https://stackoverflow.com/a/31971940中所述 ,當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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.