简体   繁体   中英

Erase the highlight JavaScript getSelection function

在此输入图像描述

highlight is not a problem. my problem is, on how can i erase the highlight using window.getSelection() in javascript. and create a node new span closing and new span opening to erase the selected highlight areas. See the 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));
        } 
    }

so far that is my function but createTextNode() can't read htmlEntities.

To achieve your expected result , follow below option

1.Get selected text from button-Toggle using id- toggle
2.Add close tag before selection element and span tag with class -'hlt' using substring

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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