如何将文本插入到当前光标位置的文本区域中

如何将文本插入到当前光标位置的文本区域中

要在文本区域/输入框的当前光标位置插入文本,我们需要获取光标的当前位置。因此,这里是获取光标当前位置的方法。

  • 首先,使用名为selectionStart的属性来获取光标的当前位置。
  • 为了在给定的位置插入文本,我们将使用slice函数将字符串分为两部分,然后将这两部分分别附加到文本(text_to_insert)的开头和结尾。

语法:

// will give the current position of the cursor
document.getElementById("id").selectionStart; 

// will get the value of the text area
let x= ('#text1').val();

// will get the value of the input box
let text_to_insert=('#insert').val();

// setting the updated value in the text area
$('#text1').val(x.slice(0,curPos)+text_to_insert+x.slice(curPos));
JavaScript

示例: 在这个示例中,我们将在当前光标位置插入文本到文本框

<!DOCTYPE html> 
<html lang="en"> 
    <head> 
        <meta charset="UTF-8" /> 
        <meta name="viewport"
              content="width=device-width,  
                       initial-scale=1.0" /> 
        <script src= 
"https://code.jquery.com/jquery-3.5.1.min.js" 
                integrity= 
"sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" 
                crossorigin="anonymous"> 
      </script> 
        <title>Document</title> 
    </head> 
    <body> 
        <textarea rows="4" 
                  id="text1" 
                  cols="50"> 
      </textarea> 
        <input type="text" 
               id="insert" /> 
        <button onclick="setTextToCurrentPos()"> 
          Insert at current position 
      </button> 
        <script> 
            function setTextToCurrentPos() { 
                var curPos =  
                    document.getElementById("text1").selectionStart; 
                console.log(curPos); 
                let x = ("#text1").val(); 
                let text_to_insert =("#insert").val(); 
                $("#text1").val( 
x.slice(0, curPos) + text_to_insert + x.slice(curPos)); 
            } 
        </script> 
    </body> 
</html>
HTML

输出:

如何将文本插入到当前光标位置的文本区域中

解释: 这里,一个命名为 setTextToCurrentPos 的编写方法被调用。 在单击 在当前位置插入 时,将调用此方法。

//document.getElementById('text1').selectionStart;
JavaScript

这一行给出了光标的当前位置/起始位置。例如: 我是一名开发者

如果我们的光标刚好放在开发者之前,那么它将返回7。因此,根据代码中示例所示,我们可以使用slice方法在当前光标位置插入文本。

let x= ('#text1').val(); // will get the value of the text area
let text_to_insert=('#insert').val(); 
// will get the value of the input box

$('#text1').val(x.slice(0, curPos)+text_to_insert+x.slice(curPos));
// setting the updated value in the text area
JavaScript

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册