Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/419.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/1/ssh/2.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-StartOffset忽略html标记_Javascript_Jquery - Fatal编程技术网

Javascript-StartOffset忽略html标记

Javascript-StartOffset忽略html标记,javascript,jquery,Javascript,Jquery,我编写了一些概念验证代码来获取突出显示的文本,并将其包装在一个范围内。如果有人选择已经包装在跨距中的文本,我也希望将该跨距包装在内部。除了稍后第二次尝试在div中包装跨度外,这一切都很好,因为起始偏移量忽略了所有插入的HTML标记。有什么办法可以让这一切顺利进行吗?无法使用indexOf,因为存在相同单词的可能性 $(function () { $('#highlightSelectLnk').click(function (event) { event.preventD

我编写了一些概念验证代码来获取突出显示的文本,并将其包装在一个范围内。如果有人选择已经包装在跨距中的文本,我也希望将该跨距包装在内部。除了稍后第二次尝试在div中包装跨度外,这一切都很好,因为起始偏移量忽略了所有插入的HTML标记。有什么办法可以让这一切顺利进行吗?无法使用indexOf,因为存在相同单词的可能性

$(function () {
    $('#highlightSelectLnk').click(function (event) {
        event.preventDefault();
        var startOffset = 0;
        var html = "";
        if (typeof window.getSelection != "undefined") {
            var sel = window.getSelection();
            if (sel.rangeCount) {
                var container = document.createElement("div");
                startOffset = sel.getRangeAt(0).startOffset;
                for (var i = 0, len = sel.rangeCount; i < len; ++i) {
                    container.appendChild(sel.getRangeAt(i).cloneContents());
                }
                html = container.innerHTML;
            }
        } else if (typeof document.selection != "undefined") {
            if (document.selection.type == "Text") {
                html = document.selection.createRange().htmlText;
            }
        }

        var text = $('#editableContent').html();
        var replacedText = text.substring(0, startOffset) +
            '<span class="highlightedText">' + html + '</span>' + text.substring(startOffset + html.length, text.length);
        $('#editableContent').html(replacedText);

    });
});

Fiddle:

最终目标是将突出显示的项目涂成红色吗?@SpencerWieczorek否。这只是最终用数据属性将文本包装到跨域中的POC,其中html将传递回后端进程进行解析。