Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
650 views
in Technique[技术] by (71.8m points)

javascript - How to get the text of a selection over multiple HTML elements?

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...