简体   繁体   English

在JQuery或JavaScript中用span元素包装突出显示的文本

[英]Wrap the highlight text with span element in JQuery or JavaScript

This my code but there is an error if you override the highlighted text. 这是我的代码,但是如果您覆盖突出显示的文本,则会出现错误。
The error is: 错误是:

Uncaught InvalidStateError: Failed to execute 'surroundContents' on 'Range': The Range has partially selected a non-Text node. 未捕获的InvalidStateError:无法在“ Range”上执行“ surroundContents”:Range已部分选择了非Text节点。

JS JS

function surroundSelection() {
  var span = document.createElement("span");
  span.setAttribute('class', 'hlt')

  if (window.getSelection) {
    var sel = window.getSelection();
    if (sel.rangeCount) {
      var range = sel.getRangeAt(0).cloneRange();
      range.surroundContents(span);
      sel.removeAllRanges();
      sel.addRange(range);
    }
  }
}     

Try this instead: 尝试以下方法:

function surroundSelection() {       
    var selection= window.getSelection().getRangeAt(0);
    var selectedText = selection.extractContents();
    var span= document.createElement("span");
    span.setAttribute('class', 'hlt')
    span.appendChild(selectedText);
    selection.insertNode(span);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM