使用Javascript选择单词的索引 [英] Index of selected words using Javascript

查看:104
本文介绍了使用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));        
}

这篇关于使用Javascript选择单词的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆