Javascript:如何un-surroundContents范围

Zeb*_*bra 5 javascript dom

此函数使用范围对象返回用户选择并将其包装为粗体标记.有没有一种方法可以删除标签?如在<b>text<b> = text.


我实际上需要一个切换功能,它将选择包装在标签中,如果已经包含标签,则将其解包.与切换粗体按钮时文本编辑器的操作类似.

if "text" then "<b>text</b>"
else "<b>text</b>" then "text"  
Run Code Online (Sandbox Code Playgroud)

...

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);
    } 
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*own 5

我之前的问题中没有提到这一点,因为它听起来像是你想要一个通用的方法来围绕一个元素中的范围,但对于这个特定的应用程序(即粗体/解开文本),并假设你不介意所使用的精确的标签小跨浏览器的变化(<strong>相对于<bold>对可能<span style="font-weight: bold">),你最好使用document.execCommand(),这将切换气魄:

function toggleBold() {
    document.execCommand("bold", false, null);
}
Run Code Online (Sandbox Code Playgroud)

当所选内容可编辑时,即使在IE中无法编辑,这也适用于所有浏览器.如果您需要在其他浏览器中处理不可编辑的内容,则需要暂时​​使文档可编辑:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • `execCommand` 已弃用。 (2认同)