简体   繁体   English

粘贴后IE9输入setSelectionRange()不起作用

[英]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: 重现步骤:

  1. Open IE in IE9-Mode 在IE9模式下打开IE
  2. Open fiddle below 在下面打开小提琴
  3. Type into the input-field (works ok, the caret gets set to 0) 键入输入字段(可以,插入符号设置为0)
  4. Paste something into the input-field (fails, the caret gets set to the end of the pasted text) 将某些内容粘贴到输入字段中(失败,插入符号设置为粘贴文本的末尾)

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 . 这是更新的小提琴

Update 更新

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);
});

Here is a Fiddle . 这是小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM