【问题标题】:Get DOM element at caret position在插入符号位置获取 DOM 元素
【发布时间】:2023-12-25 09:26:02
【问题描述】:

我正在寻找一种可靠的方法来查找页面上活动插入符号的位置。我学到了以下东西(至少关于 chrome):

  • 每个输入和文本区域都有自己单独的插入符号
  • 页面上只能“激活”一个插入符号,这意味着如果您按箭头键,则只有一个插入符号会受到影响
  • 活动插入符号不一定必须在元素 document.activeElement 内(例如,如果您使用 inputDomNode.setSelectionRange,则之前聚焦的任何元素都会保持聚焦)。

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

【问题讨论】:

标签: javascript dom selection caret textselection


【解决方案1】:

您可能想查看 Selection API 和 window.getSelection()https://developer.mozilla.org/en-US/docs/Web/API/Window.getSelection https://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。

【讨论】:

  • 所以至少在 chrome 中,focusNode 不是输入元素。出于某种原因,它是输入元素的父元素。