如何在文本区域中的末尾设置光标
How to set cursor at the end in a textarea?
有没有办法在textarea
元素中设置光标的末尾?我使用的是Firefox 3.6,我不需要它在IE或Chrome中工作。似乎这里所有相关的答案都使用onfocus()
事件,这似乎毫无用处,因为当用户单击textarea
元素中的任意位置时,Firefox 会将光标位置设置为那里。我有一个很长的文本要在textarea
中显示,以便它显示最后一部分(以便在末尾添加内容更容易)。
没有框架或库。
可能有很多方法,例如
element.focus();
element.setSelectionRange(element.value.length,element.value.length);
http://jsfiddle.net/doktormolle/GSwfW/
selectionStart 足以设置初始光标点。
element.focus();
element.selectionStart = element.value.length;
我已经很久没有先看 jQuery 解决方案就使用 javascript 了......
话虽如此,使用 javascript 的最佳方法是在文本区域中当前处于焦点时获取值,并将文本区域的值设置为抓取的值。这在jQuery中总是像这样工作:
$('textarea').focus(function() {
var theVal = $(this).val();
$(this).val(theVal);
});
在普通的javascript中:
var theArea = document.getElementByName('[textareaname]');
theArea.onFocus = function(){
var theVal = theArea.value;
theArea.value = theVal;
}
我可能是错的。有点生锈。
var t = /* get textbox element */ ;
t.onfocus = function () {
t.scrollTop = t.scrollHeight;
setTimeout(function(){
t.select();
t.selectionStart = t.selectionEnd;
}, 10);
}
诀窍是在浏览器处理完焦点事件后使用 setTimeout 更改文本插入(克拉)位置;否则位置将由我们的脚本设置,然后立即由浏览器设置为其他位置。
这是一个函数
function moveCaretToEnd(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();
}
}
[演示][来源]
textarea.focus()
textarea.value+=' ';//adds a space at the end, scrolls it into view
(this.jQuery || this.Zepto).fn.focusEnd = function () {
return this.each(function () {
var val = this.value;
this.focus();
this.value = '';
this.value = val;
});
};
@Dr.Molle的答案是正确的。 只是为了增强,您可以与 prevent-default 结合使用。
http://jsfiddle.net/70des6y2/
样本:
document.getElementById("textarea").addEventListener("mousedown", e => {
e.preventDefault();
moveToEnd(e.target);
});
function moveToEnd(element) {
element.focus();
element.setSelectionRange(element.value.length, element.value.length);
}
相关文章:
- 将文本插入光标所在的文本区域
- 提交表单后,Watir文本框输入未持续(重置为以前的文本框输入)
- 使用jQuery重置文本,同时存在AJAX调用
- 无法在Chrome控制台中使用javascript将焦点和光标设置为输入文本
- jQuery/Javascript>on单击将文本放置在最后一个已知的光标位置
- 当用户单击按钮(在光标位置)时,在输入字段中添加一个文本字符串
- 如何在按键事件发生后获取文本光标的位置
- 同时在两个文本框上显示光标
- 我可以通过javascript在鼠标光标旁边动态添加文本吗?
- 将光标放在 javascript 文本框的末尾
- jQuery - 光标后面的文本
- 测试光标是否位于文本区域中的第一行(使用软换行符)
- ContentEditable元素--将光标移回可编辑文本的开头
- 如何更改文本区域中闪烁的光标/插入符号
- 当我单击画布并拖动鼠标时,光标将变为文本选择光标.我该如何防止这种情况发生
- 在光标位置的文本区域中插入一个字符串,并进行一些更改
- 重置javascript文本框
- 按下“按钮--重置”后文本未更改
- 如何重置Raphael文本元素的bbox数据
- 防止“向上箭头”;键在文本框内重置光标位置