问题:
当某个文本框获得焦点时,将插入符号设置为文本框的末尾。解决方案需要在IE7、Opera、Chrome和Firefox中运行。
为了使事情变得更加容易,只在当前文本框的值是固定值(比如“INIT”)时需要这种行为。
不完整的解决方案:
人们会认为这很简单,但我找不到一个适用于所有浏览器的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)
我已经搭建好了一个JSFiddle。