js設(shè)置光標(biāo)位置

字號(hào):


    function getcaret(textbox)
    {
    var control = document.activeelement;
    textbox.focus();
    var rang = document.selection.createrange();
    rang.setendpoint(starttostart,textbox.createtextrange())
    control.focus();
    return rang.text.length;
    }
    function setcaret(textbox,pos)
    {
    try
    {
    var r =textbox.createtextrange();
    r.movestart('character',pos);
    r.collapse(true);
    r.select();
    }
    catch(e)
    {}
    }
    function selectlength(textbox,start,len)
    {
    try
    {
    var r =textbox.createtextrange();
    r.moveend('character',len-(textbox.value.length-start));
    r.movestart('character',start);
    r.select();
    }
    catch(e)
    {//alert(e.description)}
    }
    function insertatcaret(textbox,text)
    {
    textbox.focus();
    document.selection.createrange().text = text;
    }