how to set focus in required index on textbox for

2019-09-05 13:00发布

i'm having a textbox where i need to set focus/ cursor at required index of the textbox in opera browser.

2条回答
劫难
2楼-- · 2019-09-05 13:46

ur code works fine, but getting clash in opera.

becoz the following code snippet

if(elem.createTextRange) {

is also true to opera, but createTextRange 'll only supported by IE.

So i have changed little modification in ur code

function SetCaretPosition(elemId, caretPos) {
    var elem = document.getElementById(elemId);

    if (elem != null) {
        if ($.browser.msie) {
            if (elem.createTextRange) {
                var range = elem.createTextRange();
                range.move('character', caretPos);
                range.select();
            }
        }
        else {
            if (elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}
查看更多
爷的心禁止访问
3楼-- · 2019-09-05 13:49

Working Demo

function SetCaretPosition(elemId, caretPos) {
    var elem = document.getElementById(elemId);

    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}

elemId: id of the element

caretPos: position of the cursor

查看更多
登录 后发表回答