簡體   English   中英

如何更改文本區域中的光標位置?

[英]How to change the cursor position in a text-area?

我正在開發一個實時 HTML 編輯器。 它基本上適用於移動用戶。 所以我制作了一個帶有 HTML 標簽的虛擬鍵盤。 但我面臨一個問題,那就是 :: 鍵盤只在另一個標簽的末尾打印標簽。 所以它不能像我想要的那樣工作。

這是一個演示代碼。

    <body>

    <div id="keyboard" class="show">

    <div>
    <input type="button" value="Q">
     <input type="button" value="W">
     .........
     <input type="button" value="V">
     <input type="button" value="B">
     <input type="button" value="N">
     <input type="button" value="M">
    </div><div>
     <input id="back" type="button" value="&#8592;">
     <input id="space" type="button" value=" ">
     <input id="clear" type="reset" value="clear">
    </div><div>
    <label>Track Search</label> - <input id="text" type="text">
    </div>

    <!-- #keyboard --></div>

    <script>
    (function() {
      'use strict';
       var i, c, t, delay = 5000, kb = document.getElementById('keyboard');
    /* get all the input elements within the div whose id is "keyboard */
       i = kb.getElementsByTagName('input'); 
    /* loop through all the elements */   

    for(c = 0;c < i.length; c++) {
    /* find all the the input type="button" elements */
    if(i[c].type === 'button') { 
    /* add an onclick handler to each of them  and set the function to call */
       i[c].addEventListener('onclick',makeClickHandler(c));
       }
     }

    /* this is the type="reset" input */
       document.getElementById('clear').addEventListener('click',
       function() {
    /* remove all the characters from the input type="text" element */
     document.getElementById('text').value = '';
       },false);

    function makeClickHandler(c) {
        i[c].onclick=function() {
    /* find the non-text button  which has an id */
    if(i[c].id === 'back') {
    /* remove last character from the input the type="text" element using regular expression */
        document.getElementById('text').value =
        document.getElementById('text').value.replace(/.$/,'');
     }
    /* find the text buttons */
    else {
    /* add characters to the input type="text" element */
        document.getElementById('text').value+= this.value.toLowerCase();
       }
      };
     }
      document.onmousemove = resetTimer;
      document.onkeypress = resetTimer;

    function logout() {
     kb.classList.remove('show');
     kb.classList.add('hide');
     }

    function resetTimer() {
        clearTimeout(t);
        t = setTimeout(logout, delay)
         }
       resetTimer();
    })();
    </script>

    </body>

使用此代碼,我只能在最后一個打印字符之后打印。 但我想要那樣 [這里 '|' 表示光標],

<div><p id=".."><img src=".." />|<p/></div>

但它打印成這樣

<div><div><p><p><img src=".." />|

那么我能做些什么來解決這個問題呢?

如果您想將光標放在文本區域內容末尾之前 5 個字符

var myTextArea = document.getElementById("text");
var end = myTextArea.selectionEnd;
myTextArea.focus();
myTextArea.selectionEnd = end + 5;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM