Javascript find occurance position of selected text in a div

前端 未结 2 1371
被撕碎了的回忆
被撕碎了的回忆 2020-12-17 05:49

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

 
hello hai hello hello hello
相关标签:
2条回答
  • 2020-12-17 06:21

    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);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-17 06:47

    You'll need to use the Range capabilities of the DOM. Here is how to get the currently selected range:

    var currentRange = window.getSelection().getRangeAt(0);
    

    From there currentRage.startOffset will tell you the position of your selection within the file. So you'll need to compare that with the start range of your element:

    var myContent = document.getElementById('content');
    var divRange = document.createRange ();
    divRange.selectNodeContents (myContent);
    

    Now you can compare the divRange.startOffset with your selection startOffset and determine which one you're on.

    0 讨论(0)
提交回复
热议问题