在插入符号位置获取DOM元素

Get DOM element at caret position

本文关键字:DOM 元素 获取 位置 插入 符号      更新时间:2024-02-27

我正在寻找一种强大的方法来查找页面上的活动插入符号

  • 每个输入和文本区域都有自己单独的插入符号
  • 页面上只能有一个插入符号处于"活动"状态,这意味着如果按箭头键,则只有一个插入字符会受到影响
  • 活动插入符号不必在元素文档中。activeElement(例如,如果使用inputDomNode.setSelectionRange,则先前聚焦的任何元素都保持聚焦)

所以我基本上想知道当你按下箭头键时,如何计算出哪个插入符号会移动。

您可能需要查看选择API和window.getSelection()。https://developer.mozilla.org/en-US/docs/Web/API/Window.getSelectionhttps://developer.mozilla.org/en-US/docs/Web/API/Selection

在你的例子中,如果你想知道窗口的插入符号当前在哪个(如果有的话)文本区域,这应该可以做到:

var ta, // textarea element
    f = window.getSelection ? window.getSelection().focusNode : undefined
if (f) {
   // if the textarea is empty, the focusNode ought to be the textarea
   if (f.nodeType === 1 && f.tagName === "textarea") {
      ta = f;
   } else if (f.nodeType === 3 && f.parentNode
              && f.parentNode.tagName === "textarea") {
      ta = f.parentNode;
   }
} else {
   // Selection API is not supported in this browser (< IE9)
   // And you will have to use another method to determine the window's
   //  current selection.
}

请注意,旧版本的IE不支持Selection API。