在插入位置获取DOM元素

时间:2015-02-20 21:55:29

标签: javascript dom selection caret textselection

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

  • 每个输入和textarea都有自己独立的插入符号
  • 页面上只有一个插入符号可以“活动”,这意味着如果按箭头键,只会有一个插入符号受影响
  • 活动插入符必须位于元素document.activeElement内(例如,如果您使用inputDomNode.setSelectionRange,之前聚焦的任何元素仍然处于焦点位置。)

所以我基本上想知道如何在按箭头键时弄清楚哪个插入符会移动。

1 个答案:

答案 0 :(得分:0)

您可能希望查看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

在你的例子中,如果你想知道窗口的插入符号当前在哪个(如果有的话)textarea,这应该可以解决问题:

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。

相关问题