如何获取多个HTML元素的选择文本? [英] How to get the text of a selection over multiple HTML elements?

查看:113
本文介绍了如何获取多个HTML元素的选择文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的问题:

当用户在WYSWYG编辑器小部件的文章或编辑区域中进行选择时,
可以选择跨越多个元素,
像锚,图像,跨度标签......甚至块级元素(但在我的问题中没有表)。



我知道如何从选择中检索Range对象
,但找不到可靠的解决方案来获取 Range 对象的内容文本。



我没有为IE寻找解决方案(它的TextRange对象有一个 .text 属性)。



谢谢!

解决方案

你看过 quirksmode 关于范围的文章?

基于这篇文章,您可以创建一个方法如下:

  function getRangeText(){

var userSelection;
if(window.getSelection){
userSelection = window.getSelection();
} else if(document.selection){
userSelection = document.selection.createRange();
}
var selectedText = userSelection;
if(userSelection.text){
selectedText = userSelection.text;
}
返回selectedText;
}

我在Mac上测试了FF5,Opera 11,Safari,如IE6和IE7。这是值得在其他IE浏览器测试,但我的猜测是它也适用于它们。


Here is my question:

When the user makes a selection in an article or in the editing area of a WYSWYG editor widget, the selection can span over multiple elements, like anchors, images, span tags... even block-level elements (but no table in my problem).

I know how to retrieve a Range object from the selection, but could not find a reliable solution to get the content text of the Range object.

I'm not looking for a solution for IE (its TextRange object has a .text property).

Thanks!

解决方案

Have you looked at the quirksmode article on Range?

Based on this article, you could create a method like this:

function getRangeText() {

    var userSelection;
    if (window.getSelection) {
        userSelection = window.getSelection();
    } else if (document.selection) {
        userSelection = document.selection.createRange();
    }
    var selectedText = userSelection;
    if (userSelection.text) {
        selectedText = userSelection.text;
    }
    return selectedText;
}

I tested this in FF5, Opera 11, Safari on the Mac, as well as IE6 and IE7. It's worth testing in the other IE browsers, but my guess is it works in them, as well.

这篇关于如何获取多个HTML元素的选择文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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