在页面上获取选定的文本和选定的节点? [英] Get selected text and selected nodes on a page?

查看:24
本文介绍了在页面上获取选定的文本和选定的节点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

选择一块文本(可能跨越许多DOM节点)时,是否可以使用JavaScript提取所选文本和节点?

When selecting a block of text (possibly spanning across many DOM nodes), is it possible to extract the selected text and nodes using Javascript?

想象一下这段 HTML 代码:

Imagine this HTML code:

<h1>Hello World</h1><p>Hi <b>there!</b></p>

如果用户从World..."开始启动 mouseDown 事件,然后在there!"之后启动 mouseUp 事件,我希望它会返回:

If the user initiated a mouseDown event starting at "World..." and then a mouseUp even right after "there!", I'm hoping it would return:

Text : { selectedText: "WorldHi there!" },
Nodes: [ 
  { node: "h1", offset: 6, length: 5 }, 
  { node: "p", offset: 0, length: 16 }, 
  { node: "p > b", offset: 0, length: 6 } 
]

我尝试将 HTML 放入文本区域,但这只会让我获得 selectedText.我还没有尝试过 元素,但这可能是另一种选择.

I've tried putting the HTML into a textarea but that will only get me the selectedText. I haven't tried the <canvas> element but that may be another option.

如果不是 JavaScript,有没有办法使用 Firefox 扩展来实现?

If not JavaScript, is there a way this is possible using a Firefox extension?

推荐答案

您会遇到坎坷,但这很有可能.主要问题是 IE 和 W3C 向选择公开了完全不同的接口,因此如果您想要跨浏览器功能,那么您基本上必须将整个内容编写两次.此外,两个界面都缺少一些基本功能.

You are in for a bumpy ride, but this is quite possible. The main problem is that IE and W3C expose completely different interfaces to selections so if you want cross browser functionality then you basically have to write the whole thing twice. Also, some basic functionality is missing from both interfaces.

Mozilla 开发者联系有关于 W3C 选择的故事.Microsoft 将他们的系统记录在 MSDN 上.我建议从 PPK 的范围介绍开始.

Mozilla developer connection has the story on W3C selections. Microsoft have their system documented on MSDN. I recommend starting at PPK's introduction to ranges.

以下是我认为可行的一些基本功能:

Here are some basic functions that I believe work:

// selection objects will differ between browsers
function getSelection () {
  return ( msie ) 
    ? document.selection
    : ( window.getSelection || document.getSelection )();
}

// range objects will differ between browsers
function getRange () {
  return ( msie ) 
      ? getSelection().createRange()
      : getSelection().getRangeAt( 0 )
}

// abstract getting a parent container from a range
function parentContainer ( range ) {
  return ( msie )
      ? range.parentElement()
      : range.commonAncestorContainer;
}

这篇关于在页面上获取选定的文本和选定的节点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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