删除突出显示JavaScript getSelection函数

《删除突出显示JavaScript getSelection函数》

突出显示不是问题.我的问题是,如何在javascript中使用window.getSelection()擦除突出显示.并创建节点新跨度关闭和新跨度打开以擦除选定的高亮区域.请参阅screenShots.

function removeHighlight(sel) {

        if(sel.anchorNode.parentNode.className == 'hlt') {
            var replacementText = sel.toString();
            range = sel.getRangeAt(0);
            range.deleteContents();
            range.insertNode(document.createTextNode(replacementText));
        } 
    }

到目前为止,这是我的函数,但createTextNode()无法读取htmlEntities.

最佳答案 要达到预期效果,请按以下选项操作

1.使用id-切换从button-Toggle获取所选文本
2.使用子字符串在class -‘hlt’的选择元素和span标记之前添加close标记

HTML:

<p>
  Lorem ipsum dolor sit amet, cursus laoreet tincidunt vel, at purus sagittis ultrices <span class="hlt">varius elit accumsan, sed nulla aenean amet, nulla ac et, imperdiet </span>fermentum nulla ipsum risus leo.
</p>
<button id="toggle">Toggle</button>

JS:

$(document).ready(function() {
  $("#toggle").click(function() {
    $('span.hlt').removeClass('hlt');

    var selection = window.getSelection();
    var text = selection.toString();
    var parent = $(selection.focusNode.parentElement);
    var oldHtml = parent.html();
    var position = oldHtml.indexOf(text);
    var end =(position*1)+selection.length
    console.log(text.length);
    var output = "<span class='hlt'>" +oldHtml.substr(0, position) + "</span>"+text+"<span class='hlt'>" + oldHtml.substr(position+text.length)+ "</span>";

    //var newHtml = oldHtml.replace(text, "</span>" + text + "<span class='hlt'>");
    parent.html(output);

  });
});

CSS:

.hlt{
  background:yellow;
}

http://codepen.io/nagasai/pen/dXkZwP

点赞