什么是最好的方法(我假设最简单的方法),以放置光标在文本的输入文本元素的末尾通过JavaScript -焦点已设置到元素?
当前回答
我以前尝试过这些建议,但没有一个对我有效(在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);}
其他回答
如果先设置值,再设置焦点,光标将始终出现在最后。
$("#search-button").click(function (event) {
event.preventDefault();
$('#textbox').val('this');
$("#textbox").focus();
return false;
});
这是用来测试的小提琴 https://jsfiddle.net/5on50caf/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);}
适用于所有浏览器和所有情况:
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 is the input element
input.focus(); //sets focus to element
var val = this.input.value; //store the value of the element
this.input.value = ''; //clear the value of the element
this.input.value = val; //set that value back.
为了让光标移动到最后,输入必须先有焦点,然后当值改变时,它才会移动到最后。如果你将.value设置为相同的值,它在chrome中不会改变。
这个问题很有趣。最令人困惑的是,我没有找到完全解决这个问题的方法。
+++++++ +++++++ +++++++ +++++++ +++++++ +++++++
你需要一个JS函数,像这样: 函数moveCursorToEnd If (!(obj.updating)) { obj。更新= true; var oldValue = obj.value; obj。Value = "; setTimeout(函数(){obj。value = oldValue;obj。更新= false;}, 100); } } 你需要在onfocus和onclick事件中调用这个。 <input type="text" value="Test Field" onfocus="moveCursorToEnd(this)" onclick="moveCursorToEnd(this) "" >
它适用于所有设备的浏览器!!!!