如何使用 JavaScript 在内容可编辑元素中设置光标位置?
为了在内容可编辑元素中设置插入符号光标位置,例如 div 标签,由 JavaScript Range 接口继承。范围是使用document.createRange()方法创建的。
方法一:
- 首先,使用上述语法创建 Range 并设置位置。
- 使用jQuery从输入标签获取用户输入
$("input']").val();
- 在按钮上单击将输入值分配给范围函数以返回 div 上的光标位置。
以下语法解释清楚:
句法:
// document.createRange() creates new range object
var rangeobj = document.createRange();
// Here 'rangeobj' is created Range Object
var selectobj = window.getSelection();
// Here 'selectobj' is created object for window
// get selected or caret current position.
// Setting start position of a Range
rangeobj.setStart(startNode, startOffset);
// Setting End position of a Range
rangeobj.setEnd(endNode, endOffset);
// Collapses the Range to one of its
// boundary points
rangeobj.collapse(true);
// Removes all ranges from the selection
// except Anchor Node and Focus Node
selectobj.removeAllRanges();
// Adds a Range to a Selection
selectobj.addRange(rangeobj);
示例 1:下面的示例说明了如何根据用户输入在内容可编辑元素 div 上设置插入光标位置。
GeeksforGeeeks
HTML stands for Hyper Text Markup Language.
It is used to design web pages using markup
language. HTML is the combination of Hypertext
and Markup language. Hypertext defines the link
between the web pages. Markup language is used
to define the text document within tag which
defines the structure of web pages. HTML is a
markup language which is used by the browser
to manipulate text, images and other content
to display it in required format.
输出:
- 入职前:
- 入职后:
方法二:
- 首先使用上述语法创建范围并设置位置。
- 按钮单击触发函数返回 div 上的光标位置。
示例 2:下面的示例说明了如何在内容可编辑元素 div 上设置插入符号光标位置。
GeeksforGeeeks
HTML stands for Hyper Text Markup Language.
It is used to design web pages using markup
language. HTML is the combination of Hypertext
and Markup language. Hypertext defines the
link between the web pages. Markup language
is used to define the text document within
tag which defines the structure of web pages.
HTML is a markup language which is used by
the browser to manipulate text, images and
other content to display it in required
format.
输出:
- 点击按钮之前:
- 点击按钮后:
参考: https://developer.mozilla.org/en-US/docs/Web/API/Range