Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/441.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何获取HTML元素的开始和结束字符索引?_Javascript_Html - Fatal编程技术网

Javascript 如何获取HTML元素的开始和结束字符索引?

Javascript 如何获取HTML元素的开始和结束字符索引?,javascript,html,Javascript,Html,试图弄清楚如何使用JavaScript获取整个HTML文档中受元素影响的字符范围我只需要与webkit兼容的代码。 我想我只是没有找到合适的术语 下面是我将使用的示例: <body> This is the way we <span class="highlight"><img src="image.png" /> search the <span class="heavy">text</span> </span>, s

试图弄清楚如何使用JavaScript获取整个HTML文档中受元素影响的字符范围我只需要与webkit兼容的代码。

我想我只是没有找到合适的术语

下面是我将使用的示例:

<body>
This is the way we 
<span class="highlight"><img src="image.png" />
search the <span class="heavy">text</span>
</span>, 
search the text, search the text, 
early in the morning!
</body>

这就是我们的方式
搜索文本
, 
搜索文本,搜索文本,
一大早!
如果我得到一个带有类高亮显示的跨度的引用。。。
我想知道突出显示跨距包含的字符的开始和结束索引,包括其子跨距中的文本,但当然不是元素声明本身的一部分字符,如“”或它们之间的任何字符。

一个简单的方法是使用。这种方法并不完美:偏移将包括空白文本节点、脚本元素中的文本节点和CSS隐藏的元素中的文本,并且不包括块元素和

元素所暗示的换行符,但可能足以满足您的要求

演示:

代码:


如果您只想获取该文本:

document.querySelectorAll(".highlight")[0].innerText

你所说的“开始和结束索引”是什么意思?你想在这里实现什么?不管是什么,这听起来不是正确的方法。这很重要,但我认为您应该只对文本节点进行深度优先遍历,然后从中找出答案。当然,这不会考虑CSS对某些特定文本元素的外观索引的影响。@Pointy:您可以使用范围来避免这种方法的复杂性,但您的警告仍然适用。@TimDown是的,您是对的;我想这就是一个范围的实际用途:-)但我不认为这会考虑隐藏元素、浮动等,对吗?@Pointy:不,你是对的。我在这个问题上花了不少功夫:宾果!谢谢我想确保这不会改变选择,而且不会!你可以在这里看到:
document.querySelectorAll(".highlight")[0].innerText