javascript - 高亮文本问题

标签 javascript select editor highlighting

我正在修复一个编辑器,但我遇到了突出显示文本的问题。

我得到了这段代码,用于检查用户突出显示的内容(代码下方有更多详细信息):

function getSelectionHTML()
{
    var iframe = document.getElementById(theEditorID);
    var win, doc = iframe.contentDocument;
    if(doc)
        win = doc.defaultView;
    else
    {
        win = iframe.contentWindow;
        doc = win.document;
    }
    var userSelection;

    if(win.getSelection)
    {
        userSelection = win.getSelection();
        if(userSelection.getRangeAt)
            var range = userSelection.getRangeAt(0);
        else
        {
            var range = document.createRange();
            range.setStart(userSelection.anchorNode, userSelection.anchorOffset);
            range.setEnd(userSelection.focusNode, userSelection.focusOffset);
        }
        var clonedSelection = range.cloneContents();
        var div = document.createElement('div');
        div.appendChild(clonedSelection);
        callIcons(div.innerHTML);
    }
    else if(doc.selection)
    {
        userSelection = document.selection.createRange();
        callIcons(userSelection.htmlText);
    }
};

当用户突出显示一些粗体文本和一些其他斜体文本时,我得到了这个输出:

<b>some text</b><i>some other text</i>

但是当用户只突出显示粗体文本时,我得到了这个输出(没有“粗体”标签):

some text

您可以在此处查看,直播 - http://brownfolder.com/06/ 突出显示一些文本后,您会看到一条提醒。

您知道我该如何解决这个问题吗?

提前致谢。

最佳答案

浏览器会因是否在选择中包含周围的标签而有所不同。如果选择完全包含在标签中,它们通常不包括周围的标签。可以从选择的开始向上遍历 DOM 并检查每个元素是否是 标记。但是,如果您正在使用的 iframe 使用 contenteditable,则不能保证它会在 标记中加粗。还有其他方法可以将文本加粗:IE 通常将 标记加粗,而 Firefox 和 WebKit 可能会使用 queryCommandState 可能更好('粗体')改为在 iframe 文档上。

关于javascript - 高亮文本问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5082854/