【问题标题】:HTML - How to get selection offsets with relatives to HTML tagsHTML - 如何使用相对于 HTML 标签的选择偏移量
【发布时间】:2012-11-25 20:39:25
【问题描述】:

假设我的 HTML 看起来像这样

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

我需要能够在进行选择时获得偏移量,而不忽略跨度标签。

例如 假设用户选择了

t<span>span</span>e

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

谢谢

【问题讨论】:

  • link [jsfiddle] (jsfiddle.net/wP8w9/2)
  • 我试过摆弄这个例子,但我不知道如何获得实际的偏移量......
  • 对不起,我的错...我回家看看。
  • (基本上我需要从包装跨度开始到它的父亲的偏移量)

标签: javascript jquery html


【解决方案1】:

我就这样解决了:

            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。 然后我简单地搜索了我添加的第一个跨度的索引,以及我添加的第二个跨度的索引来查找偏移量。

【讨论】:

    猜你喜欢
    • 2013-02-17
    • 2012-10-18
    • 2022-12-20
    • 2021-06-02
    • 1970-01-01
    • 1970-01-01
    • 2014-05-22
    • 1970-01-01
    • 2014-10-23
    相关资源
    最近更新 更多