在嵌套的html标签中获取字符偏移量 [英] Getting character offset inside nested html tags

查看:119
本文介绍了在嵌套的html标签中获取字符偏移量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的HTML代码与此类似:

 < pre> 
单词单词
单词< span>单词神秘单词< / span>
词语单词
< / pre>

我想得到关于 pre的字符mystery偏移量标记使用Javascript(native或MooTools)。我可以通过使用anchorNode属性来获取 span 标记,但我无法找到与 pre 标记相关的方法。

解决方案

您可以使用 DOM 范围 来执行此操作:

  function getCharOffsetRelativeTo(container,node,offset){
var range = document.createRange();
range.selectNodeContents(container);
range.setEnd(node,offset);
return range.toString()。length;

$ / code>

示例:

  var sel = window.getSelection(); 
var pre = document.getElementById(your_pre_id);
var offset = getCharOffsetRelativeTo(pre,sel.anchorNode,sel.anchorOffset);

注意事项:


  • 这个功能可以在所有主流浏览器上运行,除了IE <= 8以外。如果你需要IE浏览器的解决方案,那么我可以提供它。

  • 这个函数会计算< script> < style> 标记和不可见元素(由CSS隐藏 display:none )。


I've got HTML code similar to this one:

<pre>
    words words words
    words <span> words mystery words</span>
    words words words
</pre>

I'd like to get the character offset of "mystery" with respect to the pre tag using Javascript (native or MooTools). I can get it with respect to the span tag using the anchorNode property, but I can't find a way to get it with respect to the pre tag.

解决方案

You could use a DOM Range to do this:

function getCharOffsetRelativeTo(container, node, offset) {
    var range = document.createRange();
    range.selectNodeContents(container);
    range.setEnd(node, offset);
    return range.toString().length;
}

Example:

var sel = window.getSelection();
var pre = document.getElementById("your_pre_id");
var offset = getCharOffsetRelativeTo(pre, sel.anchorNode, sel.anchorOffset);

Caveats:

  • This will work in all major browsers except IE <= 8. If you need a solution for IE then I can provide it.
  • This function will count characters inside <script> or <style> tags and invisible elements (hidden by CSS display: none, for example).

这篇关于在嵌套的html标签中获取字符偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆