Javascript find occurance position of selected text in a div

前端 未结 2 1376
被撕碎了的回忆
被撕碎了的回忆 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

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

提交回复
热议问题