什么是最好的方法(我假设最简单的方法),以放置光标在文本的输入文本元素的末尾通过JavaScript -焦点已设置到元素?
当前回答
<script type="text/javascript">
function SetEnd(txt) {
if (txt.createTextRange) {
//IE
var FieldRange = txt.createTextRange();
FieldRange.moveStart('character', txt.value.length);
FieldRange.collapse();
FieldRange.select();
}
else {
//Firefox and Opera
txt.focus();
var length = txt.value.length;
txt.setSelectionRange(length, length);
}
}
</script>
我在IE9和Firefox 6中使用了这个功能。和Opera 11.x
其他回答
在这之后,我发现最好的方法是使用setSelectionRange函数,如果浏览器支持它;如果不是,则恢复使用Mike Berrow回答中的方法(即将值替换为本身)。
我还将scrollTop设置为一个高值,以防我们在一个垂直滚动的文本区域。(在Firefox和Chrome中,使用任意的高值似乎比$(this).height()更可靠。)
我已经把它作为一个jQuery插件。(如果你没有使用jQuery,我相信你仍然可以很容易地得到主旨。)
我在IE6, IE7, IE8, Firefox 3.5.5,谷歌Chrome 3.0, Safari 4.0.4, Opera 10.00中进行了测试。
它可以在jquery网站上作为PutCursorAtEnd插件使用。为方便起见,1.0版的代码如下:
// jQuery plugin: PutCursorAtEnd 1.0
// http://plugins.jquery.com/project/PutCursorAtEnd
// by teedyay
//
// Puts the cursor at the end of a textbox/ textarea
// codesnippet: 691e18b1-f4f9-41b4-8fe8-bc8ee51b48d4
(function($)
{
jQuery.fn.putCursorAtEnd = function()
{
return this.each(function()
{
$(this).focus()
// If this function exists...
if (this.setSelectionRange)
{
// ... then use it
// (Doesn't work in IE)
// Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
var len = $(this).val().length * 2;
this.setSelectionRange(len, len);
}
else
{
// ... otherwise replace the contents with itself
// (Doesn't work in Google Chrome)
$(this).val($(this).val());
}
// Scroll to the bottom, in case we're in a tall textarea
// (Necessary for Firefox and Google Chrome)
this.scrollTop = 999999;
});
};
})(jQuery);
如果输入字段只需要一个静态默认值,我通常用jQuery这样做:
$('#input').focus().val('Default value');
这似乎在所有浏览器中都有效。
超级简单(你可能需要关注input元素)
inputEl = getElementById('inputId');
var temp = inputEl.value;
inputEl.value = '';
inputEl.value = temp;
在jQuery中,这是
$(document).ready(function () {
$('input').focus(function () {
$(this).attr('value',$(this).attr('value'));
}
}
虽然我回答的太晚了,但对于以后的查询,这将是有帮助的。它也适用于contentteditable div。
从你需要在最后设置焦点的地方;写这段代码-
var el = document.getElementById("your_element_id");
placeCaretAtEnd(el);
函数是-
function placeCaretAtEnd(el) {
el.focus();
if (typeof window.getSelection != "undefined"
&& typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined") {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}