问题:
当某个文本框获得焦点时,将插入符号设置到文本框的末尾。该解决方案需要与 IE7、Opera、Chrome 和 Firefox 兼容。
为了使事情更简单一些,仅当文本框的当前值为固定值时才需要此行为。 (说“开始”)
不完整的解决方案:
人们希望这非常简单,但我找不到适用于所有浏览器的 SO 答案。以下答案不有效:
$("#test").focus(function() {
// This works for Opera only
// Also tested with $(this).val($(this).val());
if (this.value == "INIT") {
this.value = "";
this.value = "INIT";
}
});
$("#test").focus(function() {
// This works for IE and for Opera
if (this.value == "INIT") {
setCaretPosition(this, 4);
}
});
我从 SO 问题中得到了 setCaretPosition 函数,并在不同的博客上也看到了它:
function setCaretPosition(ctrl, pos) {
if (ctrl.setSelectionRange) {
//ctrl.focus(); // can't focus since we call this from focus()
// IE only
ctrl.setSelectionRange(pos, pos);
}
else if (ctrl.createTextRange) {
// Chrome, FF and Opera
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos); // Also tested with this
range.moveStart('character', pos); // and this line in comment
range.select();
}
}
fiddle
我设置了一个 jsFiddle .
最佳答案
试试这个:
$("input").on("focus", function() {
if (this.value === "INIT") {
var input = this;
setTimeout(function() {
if (input.createTextRange) {
var r = input.createTextRange();
r.collapse(true);
r.moveEnd("character", input.value.length);
r.moveStart("character", input.value.length);
r.select();
}
else {
input.selectionStart = input.selectionEnd = input.value.length;
}
}, 13);
}
});
关于javascript - 将插入符号设置为焦点文本框的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13071106/