2013-03-07 79 views
1

在輸入文本框中的值時,當我在輸入值之間輸入值時,光標會自動移動到值的末尾。如何在使用javascript鍵入時避免光標移回

<!DOCTYPE html> 
<html> 
    <body> 
     <script> 
     function truncate(x) { 
      if(x.value.length > 0) 
      {    
       x.value = x.value.replace(/^\s+/, ''); 
      } 
     } 
     </script> 

     <input id="otherText" onkeyup="javascript:truncate(this);" maxlength="12" type="text"/> 

    </body> 
</html> 
+0

[更改輸入值的可能重複,同時還允許用戶鍵入](http://stackoverflow.com/questions/72171 76 /改變輸入值,而-靜止允許最用戶到型);我認爲有更多類似的,但我找不到它們 – Bergi 2013-03-07 14:07:00

回答

0
<!DOCTYPE html> 
<html> 
<body> 



<script> 
function truncate(x){ 
var val = document.getElementById("otherText"); 

var inputTextValue = val.value; 
if(inputTextValue.length>0) 
    { 

    val.value = ''; 

} 
} 
</script> 
<input id="otherText" onkeyup="javascript:truncate(this);" maxlength="12" type="text"/> </body> 
</html> 

請注意,我不知道如何更換與特定的正則表達式的字符串。但上面的代碼只是用一個空字符串替換。您可以根據您的要求進行修改。

+0

沒有它將所有的值替換爲空,所以我們不能使用這個 – user2143039 2013-03-07 13:20:59

0

試試這個

http://jsfiddle.net/DDQSU/2/

$(function() { 

    function setCaretPosition(elemId, caretPos) { 
     var elem = 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(); 
     } 
    } 
} 

$("#otherText").on("keyup", function(event){ 
          var x = this,sel=x.selectionStart; 
          if(x.value.length > 0) 
          {    
           x.value = x.value.replace(/^\s+/g, ''); 
          } 
          setCaretPosition(x,sel); 
         }) 
       }) 

該解決方案已經擺在那裏,在 Set keyboard caret position in html textbox

這個問題是一個重複Javascript, avoid cursor moving at textbox end

相關問題