将Caret设置为focus的文本框的结尾



问题:

当某个文本框接收到焦点时,将镜片设置为文本框的末尾。该解决方案需要与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。

尝试以下:

$("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/

这应该有效:

$("#test").focus(function() {
    var $this = $(this);
    var value = $this.val();
    if (value === "INIT") {
        setTimeout(function() {
            $this.val(value);
        }, 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);

最新更新