gpt4 book ai didi

javascript - 单击 html 文本输入的顶部或底部边缘时出现奇怪的光标放置行为

转载 作者:行者123 更新时间:2023-11-28 01:17:39 24 4
gpt4 key购买 nike

当点击带有一些文本的输入时,浏览器通常会将光标/插入符号放置在您在文本中点击的位置(开始、结束、中间字母等)。但是,单击输入的最上边缘始终将光标置于文本的开头,而单击底部始终将其置于末尾。我不得不想象这是故意的。它在所有浏览器中都是一致的。但是,当您点击文本末尾并希望继续书写时,很容易产生误导/烦人,但点击的位置稍高,却发现光标位于开头。

视频示例: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();
}
}

希望这对您有所帮助,或者让您走上正轨!

关于javascript - 单击 html 文本输入的顶部或底部边缘时出现奇怪的光标放置行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51719025/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com