获取 window.getSelection().anchorNode 的属性

Get Attributes of window.getSelection().anchorNode

window.getSelection().anchorNode returns 关于用户点击开始选择的节点的很多细节,但是我怎样才能得到那个文本节点的属性,比如 classid等?

示例:

<span id="word1">Aaa</span>
<span id="word2">Bbb</span>

用户选择了这两个跨度中的某些内容,我需要知道他是从哪里开始选择的,无论是在 #word1 还是在 #word2

猜猜你需要这个:window.getSelection().anchorNode.parentNode

window.onclick = function() {
  console.log(window.getSelection().anchorNode.parentNode)
  console.log(window.getSelection().anchorNode.parentNode.className);
  console.log(window.getSelection().anchorNode.parentNode.id)
}
<p class="cls" id="p1">p tag with class="cls" and id="p1",try to select something</p>

textNodes do not have any attributes you will have to get the attributes from the element parent. The select event has spoty support so I used the mousedown event and registered the Document Object开始收听。为了控制从 100 种可能性中获取值的位置和时间(请记住,文档对象将知道 Window 对象以外的任何对象上的 mousedown 事件),我们必须建立两件事:

  1. Event.currentTarget: 事件对象的属性,表示注册到事件的元素。在Demoe.currentTarget是文档对象(document.)

  2. Event.target: 事件对象的一个属性表示原点一个事件,这是对被点击、改变、悬停等元素的花哨说法。在 Demo e.target基本上是 document.

    中的任何内容

下面的Demo演示了获取点击元素节点idand/or类的方法

演示

Demo中有详细说明

document.addEventListener('mousedown', showAttr, false);

function showAttr(e) {
  // if the node clicked is NOT document...
  if (e.target !== e.currentTarget) {
    /* if the clicked node has a class attribute...
    || log all of its classes in console
    */
    var tgt = e.target;
    if (tgt.hasAttribute('class')) {
      var cList = tgt.classList;
      console.log('class=' + cList);
    }
    /* if the clicked node has an id...
    || log its id in console
    */
    if (tgt.hasAttribute('id')) {
      console.log('id=' + tgt.id);
    }
  }
  return false;
}
.as-console-wrapper {
  width: 30%;
  margin-left: 70%;
  min-height: 100%;
}

main,
main * {
  outline: 1px solid black
}
<main id='base'>
  <h1 class='mainHeading'>Title</h1>

  <ol class='ordered list'>
    <li class='1'>One</li>
    <li class='2'>Two</li>
    <li class='3'>Three</li>
  </ol>
  Text
  <article id='post31' class='test'>
    <h2 class='postHeading'>Title</h2>
    <p class='content text'>Post content</p>
    article text
  </article>
</main>





</main>

前段时间有人问过这个问题,但我找到了一种方法,您可以通过执行以下操作来访问该属性:

window.getSelection().anchorNode.parentElement.getAttribute('your-attribute-name')

这将获取围绕所选文本的 DOM 元素,并且通过访问 DOM 元素,您可以检索它的属性。