Javascript在div中查找所选文本的出现位置

tom*_*joy 3 javascript indexing

我有一个字符串有一个单词五次.如果我选​​择了你好它应该返回4

 <div id="content">hello hai hello hello hello</div>
Run Code Online (Sandbox Code Playgroud)

获取选定的文本脚本

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

如果我选择 hai它应该返回1.

如果我选择 hello hai它应该返回1.请帮忙.

Tim*_*own 8

假设<div>保证内容是单个文本节点,这不是太难.以下内容在IE <9中不起作用,它不支持Selection和Range API.如果您需要支持这些浏览器,我可以为这个特定情况提供代码,或者您可以使用我的Rangy库.

现场演示:http://jsfiddle.net/timdown/VxTfu/

码:

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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)