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
555 views
in Technique[技术] by (71.8m points)

indexing - Javascript find occurance position of selected text in a div

I have a string with a word five times.if i selected forth hello it should return 4

 <div id="content">hello hai hello hello hello</div>

getting selected text script

<script>
 if(window.getSelection){
   t = window.getSelection();
 }else if(document.getSelection){
   t = document.getSelection();
 }else if(document.selection){
   t =document.selection.createRange().text;
 }
 </script>

If am selecting hai it should return 1.

If am selecting hello hai it should return 1. please help.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Assuming that the contents of the <div> are guaranteed to be a single text node, this is not too hard. The following does not work in IE < 9, which does not support Selection and Range APIs. If you need support for these browsers, I can provide code for this particular case, or you could use my Rangy library.

Live demo: http://jsfiddle.net/timdown/VxTfu/

Code:

if (window.getSelection) {
    var sel = window.getSelection();
    var div = document.getElementById("content");

    if (sel.rangeCount) {
        // Get the selected range
        var range = sel.getRangeAt(0);

        // Check that the selection is wholly contained within the div text
        if (range.commonAncestorContainer == div.firstChild) {
            // Create a range that spans the content from the start of the div
            // to the start of the selection
            var precedingRange = document.createRange();
            precedingRange.setStartBefore(div.firstChild);
            precedingRange.setEnd(range.startContainer, range.startOffset);

            // Get the text preceding the selection and do a crude estimate
            // of the number of words by splitting on white space
            var textPrecedingSelection = precedingRange.toString();
            var wordIndex = textPrecedingSelection.split(/s+/).length;
            alert("Word index: " + wordIndex);
        }
    }
}

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

...