javascript获取网页中所选文本的段落 [英] javascript to get paragraph of selected text in web page

查看:458
本文介绍了javascript获取网页中所选文本的段落的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在突出显示文本后,我想获取所选文本所在的段落。

After highlighting text, I would like to obtain the paragraph in which the selected text resides.

var select = window._content.document.getSelection();

请指点?

推荐答案

这实际上很难做到,因为你必须考虑六种情况:

This is actually rather hard to do because you have to consider six cases:


  1. 选择不在一段(简单);

  2. 整个选择在一个段落内(简单);

  3. 整个选择跨越一个或多个兄弟段落(更难) );

  4. 选择以不在段落内的元素开始或结束(更难);

  5. 跨越的段落处于不同的级别,例如在列表项目中,而另外两个是列表的兄弟姐妹(甚至更难);和

  6. 以上的一些组合。

  1. The selection is not within a paragraph (easy);
  2. The entire selection is within one paragraph (easy);
  3. The entire selection crosses one or more sibling paragraphs (harder);
  4. The selection starts or ends in an element not within a paragraph (harder);
  5. The paragraphs spanned are at different levels eg one is within a list item while two others are siblings of the list (even harder); and
  6. Some combination of the above.

首先你必须决定你的完整程度想要解决方案。我只会介绍(1)和(2)中最简单的情况。

So firstly you have to decide how complete you want the solution to be. I'll only cover the simplest cases of (1) and (2).

function getSelectedParagraphText() {
  if (window.getSelection) {
      selection = window.getSelection();
  } else if (document.selection) {
      selection = document.selection.createRange();
  }
  var parent = selection.anchorNode;
  while (parent != null && parent.localName != "P") {
    parent = parent.parentNode;
  }
  if (parent == null) {
    return "";
  } else {
    return parent.innerText || parent.textContent;
  }
}

注意:如果你标签后面的内容也替换了innerHTML的textContent。

Note: If you're after tags too replace textContent with innerHTML.

编辑:更好的版本,包括更好的浏览器兼容性。

Better version put in, including better browser compatibility.

这篇关于javascript获取网页中所选文本的段落的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆