javascript - 输入字段属性 selectionStart / selectionEnd 延迟更新
问题描述
两个 EventListener(click
和select
) 记录输入字段属性selectionStart
和selectionEnd
.
在输入字段中选择一个范围 (通过双击或鼠标选择),EventListenerselect
被触发,selectionStart
并按selectionEnd
预期记录(selectionStart < selectionEnd
)。
然后在输入字段内单击以清除选择并显示插入符号。EventListenerclick
被触发,selectionStart
并再次使用相同的值selectionEnd
记录( )。selectionStart < selectionEnd
然后再次在输入字段内单击。EventListenerclick
再次被触发,selectionStart
并selectionEnd
使用正确的值( 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/ )
我的猜测是,更新节点需要时间,因此第一次单击会读取旧值。这可以通过一个测试功能来确认,该功能会在很短的时间间隔内读取选择。这会在第一次点击之后和第二次点击之前读取正确的值。
解决方案
推荐阅读
- java - 如何使用 gradle 为 servlet 创建 MANIFEST.MF 文件?
- python - 标头没有带有“传输编码”的“内容长度”:“分块”
- java - 使用Apache POI将多种数据类型数据从excel发送到Testng Dataprovider的最佳方法是什么
- java - DatePicker setMinDate 仅在第一次工作
- java - JAVA中未知数的平均值
- python - 如何将日志消息转储到单独的文本文件 Selenium Python
- javascript - Django - 搜索字段
- ruby-on-rails - 如何将 ActiveRecord::Relation 值传输到邮件作业?
- python-3.x - 用于打印函数执行的表达式结果的 Python 装饰器
- r - 降低水平以将其中 2 个视为控制案例。回归/建模/统计问题,因为它不是虚拟的?