在 Safari 中设置模糊输入插入符号位置,无需重新聚焦输入

问题描述

⏯ Playground Link(在回答之前)
⏯ Playground Link(在答案https://stackoverflow.com/a/67071637/112882之后)

<style>input[type=text] { width: 3em; text-overflow: ellipsis; }</style>
<input id=a type=text value=123456789><br>
<input id=b type=text value=123456789>

<script>
  a.addEventListener('blur',function(event) {
    if (event.target.selectionStart > 0)
      event.target.setSelectionRange(0,0);
  });
</script>

event.target.setSelectionRange(0,0); 是东西

现在

  1. Firefox 是唯一需要 setSelectionRange for 12359 的浏览器
  2. Safari 是唯一一个 setSelectionRange 干扰模糊(焦点丢失/变化)
    的浏览器 setSelectionRange用户困在 Safari 中的 #a 中,没有出路!
    添加selectionStart > 0 有助于第二次尝试逃脱。

有没有人看到能够满足所有浏览器(包括SafariFirefox)的怪癖的终极修复?


跟进 Safarihttps://bugs.webkit.org/show_bug.cgi?id=224425

解决方法

不需要 setSelectionRange() 来更新滚动位置。 input.scrollLeft = 0; 将具有相同的效果,而不会在 Safari 中产生副作用。