[removed] how to un-surroundContents range

后端 未结 1 1713
渐次进展
渐次进展 2020-12-19 12:07

This function uses the range object to return user selection and wrap it in bold tags. is there a method that allows me to remove the tags? As in text

相关标签:
1条回答
  • 2020-12-19 12:49

    I didn't mention this in your previous question about this because it sounded like you wanted a generic means of surrounding a range within an element, but for this particular application (i.e. bolding/unbolding text), and assuming you don't mind a little cross-browser variation in the precise tags used (<strong> versus <bold> versus possibly <span style="font-weight: bold">), you're best off using document.execCommand(), which will toggle boldness:

    function toggleBold() {
        document.execCommand("bold", false, null);
    }
    

    This will work in all browsers when the selected content is editable, and even when it's not editable in IE. If you need it to work on non-editable content in other browsers, you'll need to temporarily make the document editable:

    function toggleBold() {
        var range, sel;
        if (window.getSelection) {
            // Non-IE case
            sel = window.getSelection();
            if (sel.getRangeAt) {
                range = sel.getRangeAt(0);
            }
            document.designMode = "on";
            if (range) {
                sel.removeAllRanges();
                sel.addRange(range);
            }
            document.execCommand("bold", false, null);
            document.designMode = "off";
        } else if (document.selection && document.selection.createRange &&
                document.selection.type != "None") {
            // IE case
            range = document.selection.createRange();
            range.execCommand("bold", false, null);
        }
    }
    
    0 讨论(0)
提交回复
热议问题