gpt4 book ai didi

javascript - 是否可以将光标锁定/聚焦到文本区域的最后一行?

转载 作者:行者123 更新时间:2023-11-27 23:49:37 25 4
gpt4 key购买 nike

假设我们的 html 代码中有一个 textarea
textarea 包含一些。

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Cursor Test</title>
</head>
<body>
<textarea class="text" cols="200" rows="40">
Some Random text.
More random text
> [fixed cursor position]
</textarea>
</body>
</html>

是否可以防止光标移动到指定位置之上或之前? (在标记为[固定光标位置]的代码中)
我想仍然可以写,但我不想超过起始位置。 (在起始位置之上或之前 -> [固定光标位置])

因此,如果焦点在 textarea 上,则在键入时光标应该移动到它的位置。 (onKeyPress,仍然能够在 textarea 中选择和标记文本)

在这种情况下 -> (至少)第 3 行,第 3 列

这可以用 JavaScript 或 JQuery 完成吗?

最佳答案

有一个小函数可以帮助你:

jQuery.fn.lockCursor = function() {

return this.each(function() { //return the function for each object

if (this.setSelectionRange) { //check if function is available

var len = $(this).val().length * 2; //avoid problems with carriage returns in text
this.setSelectionRange(len, len);

} else {

$(this).val($(this).val()); //replace content with itself
//Will automatically set the cursor to the end

}

});

};
$('.text').keypress(function(){
$(this).lockCursor(); //execute function on keypress
});

Demo

编辑

我更新了我的代码,以便可以编辑我自己添加的文本:

var selectEnd; //global variable
jQuery.fn.lockCursor = function() {
return this.each(function() {
var len = $(this).val().length * 2;
this.setSelectionRange(len, len);
});
};

$('.text').focus(function(){
$(this).lockCursor();
selectEnd = $(this).val().length; //save original length of value
});

$('.text').keypress(function(){
if($(this)[0].selectionStart < selectEnd){ //cursor position is lower then initial position
$(this).lockCursor();
}
});

解释:

$(this)[0].selectionStart 是必需的,因为它必须只是一个元素,而不是 jQuery-Object 提供的一组元素

注意:此解决方案可能不兼容所有浏览器和版本,具体取决于它们对 selectionStart 方法的支持

Demo 2

引用

setSelectionRange

关于javascript - 是否可以将光标锁定/聚焦到文本区域的最后一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27984996/

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