Pegando/setando a posição do cursor numa textarea (IE e Firefox)

2 respostas
P

olá pessoal, to com um problema sério, preciso pegar a posição do cursor numa textarea, e tb setar o cursor numa posição que eu passar por parametro…

tenho esse código aqui, mas nao funciona no IE:

function doGetCaretPosition (oField) {

     // Initialize
     var iCaretPos = 0;

     // IE Support
     if (document.selection) { 

       // Set focus on the element
       oField.focus ();
  
       // To get cursor position, get empty selection range
       var oSel = document.selection.createRange ();
  
       // Move selection start to 0 position
       oSel.moveStart ('character', -oField.value.length);
  
       // The caret position is selection length
       iCaretPos = oSel.text.length;
     }

     // Firefox support
     else if (oField.selectionStart || oField.selectionStart == '0')
       iCaretPos = oField.selectionStart;

     // Return results
     return (iCaretPos);
   }

function doSetCaretPosition (oField, iCaretPos) {

     // IE Support
     if (document.selection) { 

       // Set focus on the element
       oField.focus ();
  
       // Create empty selection range
       var oSel = document.selection.createRange ();
  
       // Move selection start and end to 0 position
       oSel.moveStart ('character', -oField.value.length);
  
       // Move selection start and end to desired position
       oSel.moveStart ('character', iCaretPos);
       oSel.moveEnd ('character', 0);
       oSel.select ();
     }

     // Firefox support
     else if (oField.selectionStart || oField.selectionStart == '0') {
       oField.selectionStart = iCaretPos;
       oField.selectionEnd = iCaretPos;
       oField.focus ();
     }
}

se alguem puder me ajudar… ficarei grato… valeu

2 Respostas

P

resolvi o problema…

código:

<td class="field03">
	<input type="button" 
           class="button"
           onclick="setTag(document.forms[0].camposEspeciais.value);"
	   value="<bean:message key='produto.inserir'/>" >
</td>


//** Prototype utilizado para pegar a posicao do cursor numa textArea
Selection = function(input){
    this.isTA = (this.input = input).nodeName.toLowerCase() == "textarea";
};
with({o: Selection.prototype}){
    o.setCaret = function(start, end){
        var o = this.input;
        if(Selection.isStandard)
            o.setSelectionRange(start, end);
        else if(Selection.isSupported){
            var t = this.input.createTextRange();
            end -= start + o.value.slice(start + 1, end).split("\n").length - 1;
            start -= o.value.slice(0, start).split("\n").length - 1;
            t.move("character", start), t.moveEnd("character", end), t.select();
        }
    };
    o.getCaret = function(){
        var o = this.input;
        if(Selection.isStandard)
            return {start: o.selectionStart, end: o.selectionEnd};
        else if(Selection.isSupported){
            var s = (this.input.focus(), document.selection.createRange()), r, start, end, value;
            if(s.parentElement() != o)
                return {start: 0, end: 0};
            if(this.isTA ? (r = s.duplicate()).moveToElementText(o) : r = o.createTextRange(), !this.isTA)
                return r.setEndPoint("EndToStart", s), {start: r.text.length, end: r.text.length + s.text.length};
            for(var $ = "[###]"; (value = o.value).indexOf($) + 1; $ += $);
            r.setEndPoint("StartToEnd", s), r.text = $ + r.text, end = o.value.indexOf($);
            s.text = $, start = o.value.indexOf($);
            if(document.execCommand && document.queryCommandSupported("Undo"))
                for(r in {0:0, 0:0})
                    document.execCommand("Undo");
            return o.value = value, this.setCaret(start, end), {start: start, end: end};
        }
        return {start: 0, end: 0};
    };
    o.getText = function(){
        var o = this.getCaret();
        return this.input.value.slice(o.start, o.end);
    };
    o.setText = function(text){
        var o = this.getCaret(), i = this.input, s = i.value;
        i.value = s.slice(0, o.start) + text + s.slice(o.end);
        this.setCaret(o.start += text.length, o.start);
    };
    new function(){
        var d = document, o = d.createElement("input"), s = Selection;
        s.isStandard = "selectionStart" in o;
        s.isSupported = s.isStandard || (o = d.selection) && !!o.createRange();
    };
}

function setTag(valor){
	var selection = new Selection(document.forms[0].descricao);
    valor !== null && selection.setText(valor);
    document.forms[0].descricao.focus();
}
G

Outra solução para quem interessar:

function getCaret(el) {
  if (el.selectionStart) { 
    return el.selectionStart; 
  } else if (document.selection) { 
    el.focus(); 

    var r = document.selection.createRange(); 
    if (r == null) { 
      return 0; 
    } 

    var re = el.createTextRange(), 
    rc = re.duplicate(); 
    re.moveToBookmark(r.getBookmark()); 
    rc.setEndPoint('EndToStart', re); 

    var add_newlines = 0;
    for (var i=0; i<rc.text.length; i++) {
      if (rc.text.substr(i, 2) == '\r\n') {
        add_newlines += 2;
        i++;
      }
    }

    return rc.text.length + add_newlines; 
  }  
  return 0; 
}
function setCaret(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();
        }
    }
}
Criado 25 de julho de 2007
Ultima resposta 28 de dez. de 2011
Respostas 2
Participantes 2