HTML - 如何获取与HTML标签相关的选择偏移量 [英] HTML - How to get selection offsets with relatives to HTML tags

查看:253
本文介绍了HTML - 如何获取与HTML标签相关的选择偏移量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的HTML看起来像这样

Suppose my HTML looks something like this

<div>
    <p> start<span>span</span>end </p>
</div>

我需要能够在做出选择时获得偏移,而不会忽略span标签。

I need to be be able to get the offsets when a selection is made, without ignoring the span tags.

例如
假设用户已选择

e.g. suppose to user selected

t<span>span</span>e

我希望得到4作为起始偏移量,24作为结束偏移量。
通过window.getSelection()获得的选择对象返回1,8,这对我来说是无用的。
我显然需要处理用户只选择内部跨度或部分跨度等的所有情况。

I want the to get 4 as starting offset and 24 as the ending offset. The selection object obtained via window.getSelection() returns 1,8, which is rather useless to me. I obviously need to handle all cases where the user selects only the inner span, or part of the span etc.

谢谢

推荐答案

我最终解决了这个问题:

I've ended up solving it thusly:

            var range = sel.getRangeAt(0);
            // inserts two spans at the beginning and end of the range, to
            // calculate the offsets
            var div = document.createElement("span");
            div.setAttribute("class", START_NODE);
            range.insertNode(div);
            range.collapse(false);
            div = document.createElement("span");
            div.setAttribute("class", END_NODE);
            range.insertNode(div);
            // gets the offsets by looking up the location of the inserted spans
            // removes them after finding the offsets (also so the starting
            // offset won't screw up the ending offset)
            comment.startOffset = p.html().indexOf('<span class="' + START_NODE + '">');
            $("." + START_NODE).remove();
            comment.endOffset = p.html().indexOf('<span class="' + END_NODE + '">');
            $("." + END_NODE).remove();
            p.html(p.html());

基本上,我在范围选择的开头添加了一个SPAN,然后折叠范围和最后添加了一个SPAN。
然后我只是搜索我添加的第一个范围的索引,以及我添加的第二个范围的索引来查找偏移量。

basically, I've added a SPAN at the beginning of the range selection, then collapsed the range and added a SPAN at the end of it. Then I simply searched for the index of the first span I've added, and the index of the second span I've added to find the offsets.

这篇关于HTML - 如何获取与HTML标签相关的选择偏移量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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