使用Javascript选择单词的索引

使用Javascript选择单词的索引

问题描述:

如何使用Javascript获取HTML中选定文本的索引?
例如,在HTML文件中,有如下段落:

How can I get the index of selected text in HTML using Javascript? For example, in an HTML file, there is paragraph like the following:


我住在印度。印度是非常美丽的国家。

I am living in India. India is the very beautiful country.

现在,如果用户选择印度那么第一句应该有 alert 5 ,如果用户选择第二行的 India ,那么就有一个 alert 6 。

Now if the user selects India in the first sentence then there should be an alert 5 and if the user selects India of second line then there is an alert 6.

如何获取用户所选单词的索引?

How can I get the index of the word that the user selected?

你可以用新的的rel =nofollow> TextRange模块。 Rangy的Range对象具有 moveStart() moveEnd()方法,可以一次扩展一个单词的范围在任何方向。

You could do this with the new TextRange module of my Rangy library. Rangy's Range object has moveStart() and moveEnd() methods which allow you to expand the range a word at a time in either direction.

下面是一个演示: http:/ /jsfiddle.net/timdown/ArMHy/

代码:

var sel = rangy.getSelection();
if (sel.rangeCount > 0) {
    var range = sel.getRangeAt(0);

    // Expand the range to contain the whole word
    range.expand("word");

    // Count all the preceding words in the document
    var precedingWordCount = 0;
    while (range.moveStart("word", -1)) {
        precedingWordCount++;
    }

    // Display results
    alert("Selection starts in word number " + (precedingWordCount + 1));        
}