将插入符号设置为焦点上的文本框结尾

时间:2012-10-25 14:42:49

标签: javascript html cross-browser

问题:

当某个文本框获得焦点时,将插入符号设置为文本框的末尾。该解决方案需要与IE7,Opera,Chrome和Firefox配合使用 为了使事情变得更容易,仅当文本框的当前值是固定值时才需要此行为。 (说'INIT')

不完整的解决方案:

有人会认为这很简单,但我找不到适用于所有浏览器的SO的答案。以下答案 NOT 工作:

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

3 个答案:

答案 0 :(得分: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/

答案 1 :(得分:0)

这应该有效:

$("#test").focus(function() {
    var $this = $(this);
    var value = $this.val();
    if (value === "INIT") {
        setTimeout(function() {
            $this.val(value);
        }, 0);
    }
});

答案 2 :(得分: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);