Javascript在div中查找所选文本的出现位置 [英] Javascript find occurance position of selected text in a div
问题描述
我有一个字符串有一个单词五次。如果我选择了你好它应该返回4
I have a string with a word five times.if i selected forth hello it should return 4
<div id="content">hello hai hello hello hello</div>
获取选定的文本脚本
<script>
if(window.getSelection){
t = window.getSelection();
}else if(document.getSelection){
t = document.getSelection();
}else if(document.selection){
t =document.selection.createRange().text;
}
</script>
如果我选择 hai
它应该返回 1
。
If am selecting hai
it should return 1
.
如果选择 hello hai
它应该返回 1
。请帮忙。
If am selecting hello hai
it should return 1
. please help.
推荐答案
假设< div>
保证是单个文本节点,这不是太难。以下不适用于IE< 9,不支持Selection和Range API。如果您需要支持这些浏览器,我可以为此特定案例提供代码,或者您可以使用我的 Rangy library。
Assuming that the contents of the <div>
are guaranteed to be a single text node, this is not too hard. The following does not work in IE < 9, which does not support Selection and Range APIs. If you need support for these browsers, I can provide code for this particular case, or you could use my Rangy library.
现场演示: 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);
}
}
}
这篇关于Javascript在div中查找所选文本的出现位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!