js 文本框光标定位末尾

javascript文本框光标定位末尾,具体代码如下:

function moveEnd(obj){
    obj.focus(); 
    var len = obj.value.length; 
    if (document.selection) { 
        var sel = obj.createTextRange(); 
        sel.moveStart('character',len); //设置开头的位置
        sel.collapse(); 
        sel.select(); 
    } else if (typeof obj.selectionStart == 'number' && typeof obj.selectionEnd == 'number') { 
        obj.selectionStart = obj.selectionEnd = len; 
    } 
} 

moveEnd($("#user_name").get(0));
//若定位光标后续有操作,则在调用时套上setTimeout
setTimeout(function() {
    moveEnd($('#bankCardNo').get(0));
}, 0);
展示评论