首页 > 解决方案 > 输入字段属性 selectionStart / selectionEnd 延迟更新

问题描述

两个 EventListener(clickselect) 记录输入字段属性selectionStartselectionEnd.

在输入字段中选择一个范围 (通过双击或鼠标选择),EventListenerselect被触发,selectionStart并按selectionEnd预期记录selectionStart < selectionEnd)。

然后在输入字段内单击以清除选择并显示插入符号。EventListenerclick被触发,selectionStart再次使用相同的值selectionEnd记录( )。selectionStart < selectionEnd

然后再次在输入字段内单击。EventListenerclick再次被触发,selectionStartselectionEnd使用正确的值( selectionStart === selectionEnd) 进行记录。

document.querySelectorAll('input').forEach(el => {
  el.addEventListener('click', (e) => {

    const selectionStart = e.target.selectionStart;
    const selectionEnd = e.target.selectionEnd;
    console.log(selectionStart, selectionEnd);

  })
})

document.querySelectorAll('input').forEach(el => {
  el.addEventListener('select', (e) => {

    const selectionStart = e.target.selectionStart;
    const selectionEnd = e.target.selectionEnd;
    console.log(selectionStart, selectionEnd);

  })
})
<input value="foobar">

(或在 jsfiddle 上:https ://jsfiddle.net/x912yfpt/1/ )

我的猜测是,更新节点需要时间,因此第一次单击会读取旧值。这可以通过一个测试功能来确认,该功能会在很短的时间间隔内读取选择。这会在第一次点击之后和第二次点击之前读取正确的值。

标签: javascriptonclickaddeventlistenerevent-listener

解决方案


推荐阅读