我有这段代码,我用它把选定的文本放在一个跨度内,用 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() 。提前谢谢!