2016-09-29 63 views
0

我試圖使翻譯使用JavaScript替換方法,它工作正常。我的問題是如何停止滾動到文本框結束,因爲當我在文本框中鍵入某些內容時,它將會替換,並且光標將移到文字的末尾。因此我無法替換或鍵入一些單詞。JavaScript替換方法停止滾動結束

HTML代碼:

<form name="inputform"> 
<input class="Search" type="text" autofocus name="searchbox" onKeyUp="transcrire()" id="Search"> 
</form> 

JavaScript代碼:

var inp; 
function transcrire() { 
inp = document.inputform.searchbox.value; 
inp = inp.replace(/a/g, "B"); 
inp = inp.replace(/i/g, "D"); 
document.inputform.searchbox.value=inp; 
} 

當我輸入 「A」 的文本框,它將替換爲 「B」。當我在文本框中輸入「i」時,它將替換爲「D」。如果你可以請給我答案在JavaScript和JQuery。只能使用這個文本框沒有其他按鈕或東西。

回答

0

只需獲得初始目標位置,並設置位置回到它是用正則表達式替換後。

var inp; 
 
$('#Search').on('keyup',function(e){ 
 
    var target = e.target, 
 
    position = target.selectionStart; 
 

 
    inp = $(this).val(); 
 
    inp = inp.replace(/a/g, "B"); 
 
    inp = inp.replace(/i/g, "D"); 
 
    $(this).val(inp); 
 
    $(this).get(0).setSelectionRange(position, position); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form name="inputform"> 
 
    <input class="Search" type="text" autofocus name="searchbox" id="Search"> 
 
</form>

+0

謝謝。請像我的引用其他明智我會阻止。再次感謝你 – user43153

0

這裏有一個例子,我從這個SO後得到:Set keyboard caret position in html textbox

function setCaretPosition(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(); 
     } 
    } 
} 
+0

如何計算的位置?如果我輸入光標自動到文本框結束。 – user43153

0

var inp; 
 
$('#Search').on('keyup',function(e){ 
 
    inp = $(this).val(); 
 
    inp = inp.replace(/a/g, "B"); 
 
    inp = inp.replace(/i/g, "D"); 
 
    $(this).val(inp); 
 
    $(this).get(0).setSelectionRange(0, 0); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<form name="inputform"> 
 
<input class="Search" type="text" autofocus name="searchbox" id="Search"> 
 
</form>

+1

此代碼光標移至文本框的開頭。我不想要它。例如,如果我鍵入了BBBDDD,並且我將在BBB「a」DDD之間鍵入「a」。因此結果將是BBBBDDD,遊標應該在BBBB_DDD中。 – user43153