gpt4 book ai didi

javascript - 使用 Javascript 的选定单词的索引

转载 作者:行者123 更新时间:2023-11-30 13:18:45 24 4
gpt4 key购买 nike

如何使用 Javascript 获取 HTML 中选定文本的索引?例如,在一个 HTML 文件中,有这样一段话:

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

现在如果用户在第一句中选择 India 那么应该有一个 alert 5 如果用户在第二行选择 India然后是 alert 6

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

最佳答案

您可以使用新的 TextRange module 来做到这一点我的Rangy library . Rangy 的 Range 对象具有 moveStart()moveEnd() 方法,可让您在任一方向一次扩展一个单词的范围。

这是一个演示: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 - 使用 Javascript 的选定单词的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11074017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com