window.getSelection() offset with HTML tags?

a 夏天 提交于 2019-12-04 09:26:16
JSuar

Update

Live Example: http://jsfiddle.net/FLwxj/61/

Using a clearSelection() function and a replace approach, I was able to achieve the desired result.

var txt = $('#Text').html();
$('#Text').html(
    txt.replace(/<\/span>(?:\s)*<span class="highlight">/g, '')
);
clearSelection();

Sources:


Below you'll find some working solutions to your problem. I placed them in order of code efficiency.

Working Solutions

  • https://stackoverflow.com/a/8697302/1085891 (live example)

    window.highlight = function() {
        var selection = window.getSelection().getRangeAt(0);
        var selectedText = selection.extractContents();
        var span = document.createElement("span");
        span.style.backgroundColor = "yellow";
        span.appendChild(selectedText);
        span.onclick = function (ev) {
        this.parentNode.insertBefore(
            document.createTextNode(this.innerHTML), 
            this
        );
        this.parentNode.removeChild(this);
        }
        selection.insertNode(span);
    }
    
  • https://stackoverflow.com/a/1623974/1085891 (live example)

    $(".content").on("mouseup", function () {
       makeEditableAndHighlight('yellow'); 
    });
    
    function makeEditableAndHighlight(colour) {
        sel = window.getSelection();
        if (sel.rangeCount && sel.getRangeAt) {
        range = sel.getRangeAt(0);
        }
        document.designMode = "on";
        if (range) {
        sel.removeAllRanges();
        sel.addRange(range);
        }
        // Use HiliteColor since some browsers apply BackColor to the whole block
        if (!document.execCommand("HiliteColor", false, colour)) {
        document.execCommand("BackColor", false, colour);
        }
        document.designMode = "off";
    }
    
    function highlight(colour) {
        var range, sel;
        if (window.getSelection) {
        // IE9 and non-IE
        try {
            if (!document.execCommand("BackColor", false, colour)) {
            makeEditableAndHighlight(colour);
            }
        } catch (ex) {
            makeEditableAndHighlight(colour)
        }
        } else if (document.selection && document.selection.createRange) {
        // IE <= 8 case
        range = document.selection.createRange();
        range.execCommand("BackColor", false, colour);
        }
    }
    
  • https://stackoverflow.com/a/12823606/1085891 (live example)

Other helpful solutions:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!