Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

dom - Javascript: how to un-surroundContents range

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 <b>text<b> = text.


I actually need a toggle function that wraps the selection in tags & un-wraps it if already contains tags. Similar to what text editors do when you toggle the bold button.

if "text" then "<b>text</b>"
else "<b>text</b>" then "text"  

...

function makeBold() {

    //create variable from selection
    var selection = window.getSelection();
        if (selection.rangeCount) {
        var range = selection.getRangeAt(0).cloneRange();
        var newNode = document.createElement("b");

            //wrap selection in tags
        range.surroundContents(newNode);

            //return the user selection
        selection.removeAllRanges();
        selection.addRange(range);
    } 
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...