Range.commonAncestorContainer - Web APIs 编辑

The Range.commonAncestorContainer read-only property returns the deepest — or furthest down the document tree — Node that contains both boundary points of the Range. This means that if Range.startContainer and Range.endContainer both refer to the same node, this node is the common ancestor container.

Since a Range need not be continuous, and may also partially select nodes, this is a convenient way to find a Node which encloses a Range.

This property is read-only. To change the ancestor container of a Node, consider using the various methods available to set the start and end positions of the Range, such as Range.setStart() and Range.setEnd().

Syntax

rangeAncestor = range.commonAncestorContainer;

Example

In this example, we create an event listener to handle pointerup events on a list. The listener gets the common ancestors of each piece of selected text, and triggers an animation to highlight them.

HTML

<ul>
  <li>Strings
    <ul>
      <li>Cello</li>
      <li>Violin
        <ul>
          <li>First Chair</li>
          <li>Second Chair</li>
        </ul>
      </li>
    </ul>
  </li>
  <li>Woodwinds
    <ul>
      <li>Clarinet</li>
      <li>Oboe</li>
    </ul>
  </li>
</ul>

CSS

The .highlight class created below uses a set of CSS @keyframes to animate a fading outline.

.highlight {
  animation: highlight linear 1s;
}

@keyframes highlight {
  from { outline: 1px solid #f00f; }
  to   { outline: 1px solid #f000; }
}
body {
  padding: 1px;
}

JavaScript

document.addEventListener('pointerup', e => {
  const selection = window.getSelection();

  if (selection.type === 'Range') {
    for (let i = 0; i < selection.rangeCount; i++) {
      const range = selection.getRangeAt(i);
      playAnimation(range.commonAncestorContainer);
    }
  }
});

function playAnimation(el) {
  if (el.nodeType === Node.TEXT_NODE) {
    el = el.parentNode;
  }

  el.classList.remove('highlight');
  setTimeout(() => {
    el.classList.add('highlight');
  }, 0);
}

Result

Specifications

SpecificationStatusComment
DOM
The definition of 'Range.commonAncestorContainer' in that specification.
Living StandardNo change.
Document Object Model (DOM) Level 2 Traversal and Range Specification
The definition of 'Range.commonAncestorContainer' in that specification.
ObsoleteInitial specification.

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:43 次

字数:5241

最后编辑:7 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文