【问题标题】:Highlighting text problem突出显示文本问题
【发布时间】:2011-07-02 06:09:23
【问题描述】:

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

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

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/ 突出显示某些文本后,您会看到一条警报。

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

提前致谢。

【问题讨论】:

    标签: javascript select editor highlighting


    【解决方案1】:

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

    【讨论】:

    猜你喜欢
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    • 2011-01-15
    • 2013-11-14
    • 1970-01-01
    • 1970-01-01
    • 2013-06-05
    相关资源
    最近更新 更多