当按下向上箭头键时,将文本光标发送到文本框焦点的末尾

when up arrow key is pressed send text cursor to the end of the textbox focus

本文关键字:文本 光标 焦点      更新时间:2023-09-26

当前,当您在文本框中按向上箭头键时,光标会跳转到文本的开头。我想覆盖这个功能,并使它,当向上箭头键被按下,它是到文本的末尾。

这是我的代码:

$("#searchBox").bind("keydown", function (e) {
    if (e.which === 38) {
            searchBox.focus();
            $current.removeClass("searchBoxResultItem-active");
            searchBox.value = searchUserInput;
            searchBox.setSelectionRange(searchBox.length, searchBox.length);
        }
});

我被告知上面的文本可以工作,但我猜因为箭头键已经设置为将代码带到开始,所以它不起作用。

如何重写此功能?

您的代码中有undefined变量。稍微简化一下你的代码,这是一个工作版本:

$("#searchBox").on("keydown", function (e) {
    if (e.which === 38) {
        e.preventDefault();
        searchBox.setSelectionRange(searchBox.value.length, searchBox.value.length);
    }
});

参见JSFiddle demo

strLenght乘以2以确保光标始终在末尾结束,Opera有时会将回车视为2个字符。

$("#searchBox").bind("keydown", function (e) {
    if (e.which === 38) {
           e.preventDefault();
           $current.removeClass("searchBoxResultItem-active");
           // Multiply by 2 to ensure the cursor always ends up at the end;
           // Opera sometimes sees a carriage return as 2 characters.
           var strLength = $(this).val().length * 2;
           this.setSelectionRange(strLength, strLength);
        }
});

参见JSFiddle Demo