首页 > 解决方案 > 单击 html 文本输入的顶部或底部边缘时出现奇怪的光标放置行为

问题描述

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

视频示例:https ://imgur.com/a/D6ex4VN

我已经看到很多关于如何将光标强制到文本末尾以响应焦点事件或其他触发器的答案。但是,如果单击该顶部边缘,我没有发现任何仅将光标强制到末尾的解决方法。据我所知,使用clickfocus事件无法从文本开头的真正点击中辨别出顶部边缘点击。

很高兴知道为什么这是一开始的默认行为。

标签: javascripthtmlcsstextinputonfocus

解决方案


我已经使用互联网多年了,但从未注意到这一点。无视。

如果您希望在用户单击输入顶部时强制光标(或插入符号,取决于您来自哪里)到最后,我会使用将单击坐标与坐标进行比较的策略点击输入的范围...

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();
    }
}

希望这会有所帮助,或者它能让你走上正轨!


推荐阅读