什么是最好的方法(我假设最简单的方法),以放置光标在文本的输入文本元素的末尾通过JavaScript -焦点已设置到元素?
当前回答
我已经尝试了以下相当大的成功在chrome
$("input.focus").focus(function () {
var val = this.value,
$this = $(this);
$this.val("");
setTimeout(function () {
$this.val(val);
}, 1);
});
简单介绍一下:
它获取每个带有类焦点的输入字段,然后将输入字段的旧值存储在一个变量中,然后将空字符串应用于输入字段。
然后等待1毫秒,再次输入旧值。
其他回答
我以前尝试过这些建议,但没有一个对我有效(在Chrome中测试了它们),所以我写了自己的代码-它在Firefox, IE, Safari, Chrome中工作得很好……
在短信中:
onfocus() = sendCursorToEnd(this);
在Javascript中:
function sendCursorToEnd(obj) {
var value = obj.value; //store the value of the element
var message = "";
if (value != "") {
message = value + "\n";
};
$(obj).focus().val(message);}
我也面临着同样的问题。这个终于对我有用了
jQuery.fn.putCursorAtEnd = = function() {
return this.each(function() {
// Cache references
var $el = $(this),
el = this;
// Only focus if input isn't already
if (!$el.is(":focus")) {
$el.focus();
}
// If this function exists... (IE 9+)
if (el.setSelectionRange) {
// Double the length because Opera is inconsistent about whether a carriage return is one character or two.
var len = $el.val().length * 2;
// Timeout seems to be required for Blink
setTimeout(function() {
el.setSelectionRange(len, len);
}, 1);
} else {
// As a fallback, replace the contents with itself
// Doesn't work in Chrome, but Chrome supports setSelectionRange
$el.val($el.val());
}
// Scroll to the bottom, in case we're in a tall textarea
// (Necessary for Firefox and Chrome)
this.scrollTop = 999999;
});
};
我们可以这样称呼它:
var searchInput = $("#searchInputOrTextarea");
searchInput
.putCursorAtEnd() // should be chainable
.on("focus", function() { // could be on any event
searchInput.putCursorAtEnd()
});
它适用于safari, IE, Chrome, Mozilla。在移动设备上,我没有尝试过这种方法。
试试下面的代码:
$('input').focus(function () {
$(this).val($(this).val());
}).focus()
适用于所有浏览器和所有情况:
function moveCursorToEnd(el) {
window.setTimeout(function () {
if (typeof el.selectionStart == "number") {
el.selectionStart = el.selectionEnd = el.value.length;
} else if (typeof el.createTextRange != "undefined") {
var range = el.createTextRange();
range.collapse(false);
range.select();
}
}, 1);
}
如果您需要从onFocus事件处理程序移动光标,需要超时
input = $('input');
input.focus().val(input.val()+'.');
if (input.val()) {input.attr('value', input.val().substr(0,input.val().length-1));}