gpt4 book ai didi

Javascript在div中查找所选文本的出现位置

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:05:06 34 4
gpt4 key购买 nike

我有一个包含单词 5 次的字符串。如果我选​​择 hello,它应该返回 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

如果我选择 hello hai,它应该返回 1。请帮忙。

最佳答案

假设 <div> 的内容保证是单个文本节点,这并不难。以下在 IE < 9 中不起作用,它不支持 Selection 和 Range API。如果您需要对这些浏览器的支持,我可以为这种特殊情况提供代码,或者您可以使用我的 Rangy图书馆。

现场演示: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中查找所选文本的出现位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11558527/

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