0

我有这段代码,我用它把选定的文本放在一个跨度内,用 CSS 给它一个背景色。当我尝试“标记”来自两个不同 div 的文本或任何两个标签内的文本时,我收到一个错误: Uncaught Error: BAD_BOUNDARYPOINTS_ERR: DOM Range Exception 1

这是我的代码:

function highlightSelection()   {
var selection;



//Get the selected stuff
    if(window.getSelection) 
        selection = window.getSelection();
    else if(typeof document.selection!="undefined")
        selection = document.selection;

    //Get a the selected content, in a range object
    var range = selection.getRangeAt(0);

    //If the range spans some text, and inside a tag, set its css class.
    if(range && !selection.isCollapsed)
    {
            var span = document.createElement('span');
            span.className = 'highlight-green';
            range.surroundContents(span);
    }
}

onmouseup使用事件调用 highlightSelection() 。提前谢谢!

4

1 回答 1

1

Range的surroundContents()方法只有在 Range 的内容可以被单个节点包围时才有效。示例相当直观。因此,在大括号表示范围边界的情况下,以下是可以的:

One {two} three
One {two <b>three</b> four} five

...虽然以下情况不好:

One {two <b>three} four</b> five
One <b>two {three</b> <i>four} five</i>

Insetad,我建议使用document.execCommand()为选择应用背景颜色,因为这将为您处理所有这些内容。我之前在 Stack Overflow 上提供了执行此操作的代码

如果你需要应用一个类,你可以使用我的Rangy库的CSS 类应用程序模块。

于 2012-11-30T15:02:33.053 回答