如何在 JavaScript 中设置内容可编辑元素的光标位置?


在 HTML 中,内容可编辑的 div 允许用户编辑 div 元素的内容。我们需要将 contenteditable 属性设置为 true 布尔值才能使任何 div 元素可编辑。

内容可编辑的 div 默认包含插入符光标,有时我们可能需要设置内容可编辑 div 元素中的插入符光标位置来编辑 div 的内容。但是,我们可以在内容可编辑的 div 中点击特定位置来设置插入符光标位置。

本教程将教我们使用不同的示例来在自定义位置设置插入符光标。

语法

用户可以按照以下语法在内容可编辑的 div 中自定义位置设置插入符光标。

var selectedText = window.getSelection();
var selectedRange = document.createRange();
selectedRange.setStart(text_div.childNodes[0], 45);
selectedRange.collapse(true);
selectedText.removeAllRanges();
selectedText.addRange(selectedRange);
text_div.focus(); 

在上述语法中,我们创建了一个范围并将其添加到选定文本中,之后,为了显示光标,我们关注了内容可编辑的 div。

步骤

用户可以按照以下步骤在内容可编辑的 div 中自定义位置设置插入符光标。

步骤 1 − 首先,使用 id、名称、标签等获取内容可编辑的 div。

步骤 2 − 之后,使用 window 对象的 getSelection() 方法从窗口中选择文本。

步骤 3 − 接下来,我们需要使用 createRange() 方法创建一个范围。

步骤 4 − 使用 range 对象的 setStart() 方法,并通过传递值作为参数来设置光标的起始位置。

步骤 5 − 接下来,使用 collapse 方法并将 true 布尔值作为参数传递,以在 div 元素的边界处折叠所有范围。

步骤 6 − 之后,使用 removeAllRange() 方法从文本中删除所有以前的范围。

步骤 7 − 现在,我们需要使用 addRanges() 方法在删除范围后将范围添加到选定文本。

步骤 8 − 使用 focus 方法将焦点设置到内容可编辑的 div 元素上。

示例

在下面的示例中,我们创建了 div 并向 div 元素中添加了一些文本。此外,我们还向 div 元素添加了 contenteditable 属性以使其可编辑。

之后,我们使用了上述算法在自定义位置设置插入符光标。在输出中,用户可以观察到,当他们刷新网页时,它会在内容可编辑的 div 中第 45 个位置设置光标。

<html>
<body>
   <h2>Setting up the <i> custom cursor position </i> in the content editable div</h2> <br>
   <div id = "text_div" contenteditable = "true" spellcheck = "false" style = "caret-color:red">
      This is a text of the content editable div. Users can click anywhere to place the cursor position. The cursor color is red. The initial cursor position is 45.
   </div>
   <script>

      // select content editable div element
      var text_div = document.getElementById("text_div");

      // select text from a window
      var selectedText = window.getSelection();
 
      // create a range
      var selectedRange = document.createRange();

      // set starting position of the cursor in the texts
      selectedRange.setStart(text_div.childNodes[0], 45);

      // collapse the range at boundaries
      selectedRange.collapse(true);

      // remove all ranges
      selectedText.removeAllRanges();

      // add a new range to the selected text
      selectedText.addRange(selectedRange);

      // focus the cursor
      text_div.focus();
   </script>
</body>
</html>

示例

在下面的示例中,我们创建了 range 输入,它获取用户的光标位置。之后,当用户点击按钮时,以下代码将获取输入值并通过将输入值作为参数来调用 setCusorPosition() 函数。

在 setCusorPosition() 函数中,我们编写了根据所解释的算法在自定义位置设置光标的代码。此外,我们还使用了 try-catch 块来捕获错误。

在输出中,用户可以观察到,设置较大的值作为输入会显示错误消息。

<html>
<body>
   <h2>Setting up the <i> custom cursor position </i> in the content editable div</h2><br>
   <div id="editable_div" contenteditable="true" spellcheck="false" style="caret-color:blue">
      TutorialsPoint is the best platform to learn programming languages such as JavaScript, TypeScript, HTML, CSS, ReactJS, Java, Python, C, C++, etc.  TutorialsPoint also provides the best courses to learn particular programming languages from different tutors.  Students can choose their favourite tutor's course and learn concepts related to computer science with full fun.
   </div> <br />
   <input type = "number" id = "cursor_range" min = "0" value = "0" max = "500" /> <br> <br>
   <div id = "output"> </div>
   <button id = "button"> Set cursor position </button>
   <script>
      let output = document.getElementById('output');
      function setCursorPosition(customPosition) {
         try {
            evar element = document.getElementById("editable_div");
            evar selected = window.getSelection();
            evar range = document.createRange();
            erange.setStart(element.childNodes[0], customPosition);
            erange.collapse(true);
            eselected.removeAllRanges();
            eselected.addRange(range); 
            element.focus();
            output.innerHTML = "";
         } catch (error) {
            output.innerHTML = "The error is " + error.message;
         }
      }
      let btn = document.getElementById('button');
      btn.addEventListener('click', () => {
         let value = document.getElementById('cursor_range').value;
         setCursorPosition(value)
      })
   </script>
</body>
</html>

用户学习了如何使用 JavaScript 在内容可编辑的 div 中设置光标位置。在第一个示例中,我们将光标设置在第 45位置,在第二个示例中,我们从用户那里获取了自定义位置。

更新于:2023年2月22日

10K+ 浏览量

启动您的职业生涯

完成课程后获得认证

开始学习
广告
© . All rights reserved.