javascript - 单击 html 文本输入的顶部或底部边缘时出现奇怪的光标放置行为
问题描述
单击其中包含一些文本的输入时,通常浏览器会将光标/插入符号放置在您在文本中单击的位置(开头、结尾、中间字母等)。但是,单击输入的最上边总是将光标放在文本的开头,而单击底部总是将光标放在末尾。我不得不想象这是故意的。它在所有浏览器中都是一致的。但是,当您点击文本末尾并希望继续写作时,它很容易产生误导/烦人,但点击的位置略高并在开头找到光标。
视频示例:https ://imgur.com/a/D6ex4VN
我已经看到很多关于如何将光标强制到文本末尾以响应焦点事件或其他触发器的答案。但是,如果单击该顶部边缘,我没有发现任何仅将光标强制到末尾的解决方法。据我所知,使用click
或focus
事件无法从文本开头的真正点击中辨别出顶部边缘点击。
很高兴知道为什么这是一开始的默认行为。
解决方案
我已经使用互联网多年了,但从未注意到这一点。无视。
如果您希望在用户单击输入顶部时强制光标(或插入符号,取决于您来自哪里)到最后,我会使用将单击坐标与坐标进行比较的策略点击输入的范围...
handleTestClick = (event) => {
// get the coordinates of the top edge of the input
// from https://stackoverflow.com/questions/442404
const rectTop = event.target.getBoundingClientRect().top;
// then get the coordinates of the click
// from https://stackoverflow.com/questions/23744605
const click = event.clientY;
//test whether the click is close enough to the top to trigger cursor to beginning
if(click - 5 <= rectTop) {
this.moveCursorToEnd(event.target);
}
}
// taken from https://davidwalsh.name/caret-end
// which draws from https://stackoverflow.com/questions/3356770
moveCursorToEnd(el) {
if (typeof el.selectionStart == "number") {
el.selectionStart = el.selectionEnd = el.value.length;
} else if (typeof el.createTextRange != "undefined") {
el.focus();
var range = el.createTextRange();
range.collapse(false);
range.select();
}
}
希望这会有所帮助,或者它能让你走上正轨!
推荐阅读
- r - 根据另一列过滤和替换列中的值
- json - jq '.[]' 不提供 jsonObjects 而是在 powershell 中提供 psobjects。如何解决这个问题?
- android - 安卓蓝牙服务器
- vue.js - 重新加载页面后数据丢失(nuxt)
- sql - 在 Postgres 中使用 generate_series 和 crosstab 时返回“记录”的函数需要列定义列表
- angular - 如何将router.module中的路由注册为子路由
- angular - 角度如何动态添加组件列表
- android - Xamarin.Forms 的 MediaManager 音量控制
- azure-devops - 安装 2019 年 12 月更新后,在 Azure DevOps Server 2019 上看不到生成的 PAT
- java - 需要在 Java 8 中清理 ResponseEntity 的主体