[英]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.
我的问题是,如何在javascript中使用window.getSelection()擦除突出显示。 and create a node new span closing and new span opening to erase the selected highlight areas.
并创建节点新跨度关闭和新跨度打开以擦除选定的高亮区域。 See the screenShots.
请参阅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. 到目前为止,这是我的函数,但createTextNode()无法读取htmlEntities。
To achieve your expected result , follow below option 要达到预期效果,请按以下选项操作
1.Get selected text from button-Toggle using id- toggle 1.使用id-切换从button-Toggle获取所选文本
2.Add close tag before selection element and span tag with class -'hlt' using substring 2.使用子字符串在class -'hlt'的选择元素和span标记之前添加close标记
HTML: 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: 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: CSS:
.hlt{
background:yellow;
}
http://codepen.io/nagasai/pen/dXkZwP http://codepen.io/nagasai/pen/dXkZwP
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.