的問題:設置插入符結束文本框的焦點
當某個文本框接收焦點,設置插入符文本框的末尾。該解決方案需要與IE7,Opera,Chrome和Firefox兼容。
爲了使事情更容易一些,只有當文本框的當前值爲固定值時才需要此行爲。 (說「INIT」)
未完成的解決方案:
人們會想到這是很簡單,但我無法找到,這樣在瀏覽器上運行的答案。以下的答案做不工作:
$("#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();
}
}
小提琴
我設置一個jsFiddle。
你能更具體地說明它在哪裏以及如何不起作用嗎? – jrajav
在FF和Chrome中,所有文本都被選中。 – Laoujin