问题
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.
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?
回答1:
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.
Here's a demo: http://jsfiddle.net/timdown/ArMHy/
Code:
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));
}
回答2:
If you want to find a string by its index, you can use-
string.match(regularExpression)[index]
Parameter Values-
regularExpression = Required. The value to search for, as a regular expression.
index = index of the regularExpression.
Now you can consider this as an object and assign event handlers to it.
来源:https://stackoverflow.com/questions/11074017/index-of-selected-words-using-javascript