setCursorPosition在chrome中不起作用

时间:2013-10-29 07:18:25

标签: javascript jquery html

移动功能Caret在Chrome中不起作用,但适用于Firefox。

$.fn.setCursorPosition = function (pos) {
        console.log(pos);
        this.each(function (index, elem) {
            console.log(index);
            console.log(elem);
            if (elem.setSelectionRange) {
                elem.setSelectionRange(pos, pos);
            } else if (elem.createTextRange) {
                var range = elem.createTextRange();
                range.collapse(true);
                range.moveEnd('character', pos);
                range.moveStart('character', pos);
                range.select();
            }
        });
        return this;
    };

代码:         var $ telInput = $('。telborder input');

    $telInput.focus(function() {
        $(".telborder").css("border", "solid 1px #cd5728");
        var getCharacters  = $telInput.val();
        var numberPosition = regexlast(getCharacters, /\d/);

        if (numberPosition >= 0) {
            $telInput.setCursorPosition(numberPosition);
        } else {
            $telInput.setCursorPosition(1);
        }
    });

2 个答案:

答案 0 :(得分:0)

function setCaret() {
    var el = document.getElementById("editable");
    var range = document.createRange();
    var sel = window.getSelection();
    range.setStart(el.childNodes[2], 5);
    range.collapse(true);
    sel.removeAllRanges();
    sel.addRange(range);
    el.focus();
}

Demo for you

答案 1 :(得分:0)

解决问题:

window.setTimeout(function() {
    elem.setSelectionRange(pos, pos);
}, 0);

完整代码:

$.fn.setCursorPosition = function (pos) {
    this.each(function (index, elem) {
        if (elem.setSelectionRange) {
            window.setTimeout(function() {
                elem.setSelectionRange(pos, pos);
            }, 0);
         } else if (elem.createTextRange) {
             var range = elem.createTextRange();
             range.collapse(true);
             range.moveEnd('character', pos);
             range.moveStart('character', pos);
             range.select();
         }
    });
    return this;
};