[英]IE9 input setSelectionRange() after paste not working
I have to manually set the caret-position to 0 in an input-field (in the input-event). 我必须在输入字段中(输入事件中)手动将插入符号位置设置为0。 I need to support >= IE9. 我需要支持> = IE9。 Even in IE9 this works ok as long as I do normal input (pressing keys on my keyboard). 即使在IE9中,只要我进行常规输入(按键盘上的键),此操作都可以。 But as soon as I use copy&paste, the caret isn't set to the desired position (0). 但是,一旦我使用复制粘贴,插入标记就不会设置为所需的位置(0)。
Steps to reproduce: 重现步骤:
Fiddle: https://jsfiddle.net/wv61t7k5/7/ 小提琴: https : //jsfiddle.net/wv61t7k5/7/
Code 码
<input type="text" />
document.querySelector('input').addEventListener('input', function(){
this.setSelectionRange(0,0);
});
Funny. 滑稽。 First I thought IE9 maybe would not fire the event on pasting, but it does. 首先,我认为IE9可能不会在粘贴时触发该事件,但确实会触发。 No idea why this would not work. 不知道为什么这行不通。
However, you could use the keyup
event. 但是,您可以使用keyup
事件。 This is definitely not as good as using input
but will work in IE9. 这绝对不如使用input
好,但可以在IE9中使用。
document.querySelector('input').addEventListener('keyup', function(e){
if (e.key != 'Left' && e.key != 'Right' &&
e.key != 'Shift' && e.key != 'Control') {
this.setSelectionRange(0,0);
}
});
To still be able to select text by keyboard, you'd have to exclude some keys. 为了仍然能够通过键盘选择文本,您必须排除一些键。
Here is an updated Fiddle . 这是更新的小提琴 。
Well, this still does not work if the user pastes text by using mouse and context menu. 好吧,如果用户使用鼠标和上下文菜单粘贴文本,这仍然不起作用。 Happily IE knows the paste
event. IE很高兴知道paste
事件。 Unhappily there is no after paste event, so you'd end up using a timeout
: 不幸的是,没有粘贴后事件,因此您最终将使用timeout
:
document.querySelector('input').addEventListener('input', function(e){
this.setSelectionRange(0,0);
});
document.querySelector('input').addEventListener('paste', function() {
var that = this;
setTimeout(function() {
that.setSelectionRange(0,0);
}, 100);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.