I want to put cursor in beginning of text-box onfocus [duplicate]

五迷三道 提交于 2019-12-04 05:12:16
Tim Down

The problem is that Chrome (I haven't heard of Safari doing this as well, but I'll take you word for it) kills the selection after the focus event has fired, so you need to add a timer. The following is adapted from my answer here:

How to place cursor at end of text in textarea when tabbed into

However, this generally isn't good usability: it's contrary to what the user expects and removes useful functionality when using the mouse (i.e. the caret going to the location the user clicks). You can probably get around that with some handling of mousedown and mouseup events.

Live demo: http://jsfiddle.net/timdown/z9DhX/1/

Code:

function moveCaretToStart(el) {
    if (typeof el.selectionStart == "number") {
        el.selectionStart = el.selectionEnd = 0;
    } else if (typeof el.createTextRange != "undefined") {
        el.focus();
        var range = el.createTextRange();
        range.collapse(true);
        range.select();
    }
}

var textBox = document.getElementById("id");

textBox.onfocus = function() {
    moveCaretToStart(textBox);

    // Work around Chrome's little problem
    window.setTimeout(function() {
        moveCaretToStart(textBox);
    }, 1);
};

Webkit is resetting the caret position as part of the focus event. You need to defer execution of your script until after the event has fully fired. Using setTimeout with a delay of 0 is good enough:

$(":text").focus(function () {
    var input = this;
    setTimeout(function() {
        input.setSelectionRange(0, 0);
    }, 0);
});

Working demo: http://jsfiddle.net/ZkqGH/1/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!