4

问题:

当某个文本框获得焦点时,将插入符号设置为文本框的末尾。该解决方案需要与 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 questions 中得到了 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

4

3 回答 3

4

试试这个:

$("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);
    }
});

http://jsfiddle.net/azBxU/4/

于 2012-10-25T14:46:08.950 回答
0

这应该有效:

$("#test").focus(function() {
    var $this = $(this);
    var value = $this.val();
    if (value === "INIT") {
        setTimeout(function() {
            $this.val(value);
        }, 0);
    }
});
于 2012-10-25T14:48:40.820 回答
0

我找到了一个为我工作了很长时间的 jQuery 插件。虽然不记得在哪里。

(function($)
{
    jQuery.fn.putCursorAtEnd = function() {
    return this.each(function() {
        $(this).focus()

        // If this function exists...
        if (this.setSelectionRange) {
            // ... then use it
            // (Doesn't work in IE)

            // Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
            var len = $(this).val().length * 2;
            this.setSelectionRange(len, len);
        } else {
            // ... otherwise replace the contents with itself
            // (Doesn't work in Google Chrome)
            $(this).val($(this).val());
        }

        // Scroll to the bottom, in case we're in a tall textarea
        // (Necessary for Firefox and Google Chrome)
        this.scrollTop = 999999;
    });
    };
})(jQuery);
于 2012-10-25T14:57:32.143 回答