Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 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 Reply

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);
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...