2013-10-29 78 views
1

在Chrome中移動插入符的功能不起作用,但在Firefox中起作用。setCursorPosition在鍍鉻中不起作用

$.fn.setCursorPosition = function (pos) { 
     console.log(pos); 
     this.each(function (index, elem) { 
      console.log(index); 
      console.log(elem); 
      if (elem.setSelectionRange) { 
       elem.setSelectionRange(pos, pos); 
      } else if (elem.createTextRange) { 
       var range = elem.createTextRange(); 
       range.collapse(true); 
       range.moveEnd('character', pos); 
       range.moveStart('character', pos); 
       range.select(); 
      } 
     }); 
     return this; 
    }; 

代碼: 變量$ telInput = $( 'telborder輸入');

$telInput.focus(function() { 
     $(".telborder").css("border", "solid 1px #cd5728"); 
     var getCharacters = $telInput.val(); 
     var numberPosition = regexlast(getCharacters, /\d/); 

     if (numberPosition >= 0) { 
      $telInput.setCursorPosition(numberPosition); 
     } else { 
      $telInput.setCursorPosition(1); 
     } 
    }); 

回答

0

解決問題:

window.setTimeout(function() { 
    elem.setSelectionRange(pos, pos); 
}, 0); 

全碼:

$.fn.setCursorPosition = function (pos) { 
    this.each(function (index, elem) { 
     if (elem.setSelectionRange) { 
      window.setTimeout(function() { 
       elem.setSelectionRange(pos, pos); 
      }, 0); 
     } else if (elem.createTextRange) { 
      var range = elem.createTextRange(); 
      range.collapse(true); 
      range.moveEnd('character', pos); 
      range.moveStart('character', pos); 
      range.select(); 
     } 
    }); 
    return this; 
}; 
0
function setCaret() { 
    var el = document.getElementById("editable"); 
    var range = document.createRange(); 
    var sel = window.getSelection(); 
    range.setStart(el.childNodes[2], 5); 
    range.collapse(true); 
    sel.removeAllRanges(); 
    sel.addRange(range); 
    el.focus(); 
} 

Demo for you