本文介绍了获取所选文本的所有DOM块元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在HTML文档中选择文本时,可以从一个DOM元素开始到另一个元素,可能会在路上传递其他几个元素。使用DOM API,可以获取所选择的文本,所选文本的范围,甚至获取所有选定的DOM元素的父元素(使用commonAncestorContainer或parentElement())。然而,我没有办法知道可以列出所有包含所选文本元素的所有文本,而不是获取包含它们的单个父元素。使用父代和遍历子节点不会这样做,因为可能还有其他兄弟姐妹在这个父母中没有选择。

When selecting texts in HTML documents, one can start from within one DOM element to another element, possibly passing over several other elements on the way. Using DOM API, it is possible to get the range of the selection, the selected texts, and even the parent element of all those selected DOM elements (using commonAncestorContainer or parentElement() based on the used browser). However, there is no way I am aware of that can list all those containing elements of the selected texts other than getting the single parent element that contains them all. Using the parent and traversing the children nodes won't do it, as there might be other siblings which are not selected inside this parent.

那么有没有办法我可以得到包含所选文本的所有这些元素。我主要感兴趣的是获取块元素(p,h1,h2,h3,...等等),但是我相信如果有办法获取所有元素,那么我可以通过它们进行过滤,以获得什么想。我欢迎任何想法和建议。

So, is there is a way that I can get all these elements that contains the selected texts. I am mainly interested in getting the block elements (p, h1, h2, h3, ...etc) but I believe if there is a way to get all the elements, then I can go through them and filter them to get what I want. I welcome any ideas and suggestions.

谢谢。

推荐答案

key是 window.getSelection()。getRangeAt(0)

以下是一些您可以使用的示例代码来执行所需的操作。提到你真正想要的这个问题可以帮助人们提供更好的答案。

Here's some sample code that you can play with to do what you want. Mentioning what you really want this for in question will help people provide better answers.

var selection = window.getSelection();
var range = selection.getRangeAt(0);
var allWithinRangeParent = range.commonAncestorContainer.getElementsByTagName("*");

var allSelected = [];
for (var i=0, el; el = allWithinRangeParent[i]; i++) {
  // The second parameter says to include the element
  // even if it's not fully selected
  if (selection.containsNode(el, true) ) {
    allSelected.push(el);
  }
}


console.log('All selected =', allSelected);

这不是最有效的方式,您可以使用Range的startContainer / endContainer自动遍历DOM,以及nextSibling / previousSibling和childNodes。

This is not the most efficient way, you could traverse the DOM yourself using the Range's startContainer/endContainer, along with nextSibling/previousSibling and childNodes.

这篇关于获取所选文本的所有DOM块元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 00:59