Set cursor at a length of 14 onfocus of a textbox

送分小仙女□ 提交于 2019-11-26 17:26:50

问题


Hai Guys, I want to set cursor at a position of length 14 on a textbox which will not have a value.. Iknow initially cursor will be at 0 i want it to be at 14


回答1:


IE use different approach at setting cursor position than Firefox,Opera and Chrome. It's better to make a helper function, which will do it for you. I use this one for own needs.

function setCursor(node,pos){

    node = (typeof node == "string" || node instanceof String) ? document.getElementById(node) : node;

    if(!node){
        return false;
    }else if(node.createTextRange){
        var textRange = node.createTextRange();
        textRange.collapse(true);
        textRange.moveEnd(pos);
        textRange.moveStart(pos);
        textRange.select();
        return true;
    }else if(node.setSelectionRange){
        node.setSelectionRange(pos,pos);
        return true;
    }

    return false;
}

Last thing, is to call it from your onfocus handler.

Goodluck




回答2:


The moveStart and moveEnd methods expects 2 parameters. The first parameter is a string (character, word, sentence or textedit). The second parameter is an integer and refers to the number of units to move. http://msdn.microsoft.com/en-us/library/ie/ms536623%28v=vs.85%29.aspx




回答3:


$("#textbox").selectionStart=14 might works for Firefox, Opera, Chrome, but not sure for IE

PS: There should be length 14 > characters already in textbox to work properly.



来源:https://stackoverflow.com/questions/1865563/set-cursor-at-a-length-of-14-onfocus-of-a-textbox

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