Javascript:如何un-surroundContents范围

时间:2010-12-18 17:21:09

标签: javascript dom

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


我实际上需要一个切换功能,将选择包装在标签和放大器中。如果已包含标签,则取消包装。与切换粗体按钮时文本编辑器的操作类似。

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

1 个答案:

答案 0 :(得分:5)

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

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

当所选内容可编辑时,即使在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);
    }
}
相关问题