function highlight_text(sel) {
span = htmlSpanHlt();
if (sel.getRangeAt) {
range = sel.getRangeAt(0);
}
span.appendChild(range.extractContents());
range.insertNode(span);
}
function htmlSpanHlt() {
element = document.createElement("span");
element.setAttribute('class', 'hlt');
return element;
}

.hlt {
background: yellow;
}

<div class="highlight">
<p>
<span class="hlt">Lorem</span> ipsum dolor sit amet, zril accusata postulant at ius. Dicat etiam luptatum ea pri. Duo docendi vulputate dissentiet ut, tollit bonorum duo eu. Maiorum adolescens scriptorem usu eu, sit idque facer causae ei. Choro nostrum at pro, sumo essent suscipiantur pri ex. Quo case veritus definiebas eu, sit postulant dissentias ei.<br>
<br>
Mel cu porro decore, cum et simul recteque inciderint. His ne omnes sententiae, ut omittantur dissentiet accommodare sed. Pro minim necessitatibus ne, no malis integre quo. Sed utroque molestiae interpretaris ne. Oportere indoctum at has, te sale semper eum, ea nam vitae dissentiet.
</p>
</div>
&#13;
&#34; Lorem&#34;有一个类名&#34; hlt&#34;这已被突出显示。我想要的是:如果我想突出另一个文字,包括“#34; Lorem&#34; w / c已经突出显示。我想合并他们的span html元素。示例:如果我突出显示&#34; ipsum&#34;旁边的单词&#34; Lorem&#34;我还包括&#34; Lorem&#34;结果将是Lorem Ipsum。有人能帮我吗?谢谢你。
答案 0 :(得分:1)
这个怎么样?
function highlight_text(sel) {
var hlt_element = document.getElementsByClassName('hlt')[0];
if (!hlt_element || sel.containsNode(hlt_element,true)) {
add_hlt_element(sel);
}
}
function add_hlt_element(sel) {
var element = document.createElement("span");
var range = sel.getRangeAt(0);
element.setAttribute('class', 'hlt');
element.innerHTML = sel.toString().replace(/(?:\r\n|\r|\n)/g, '<br />\n');
range.deleteContents();
range.insertNode(element);
var highlight_div = document.getElementsByClassName("highlight")[0];
highlight_div.innerHTML = highlight_div.innerHTML.replace('</span><span class="hlt">','');
}
window.onmouseup = function() {
var sel = window.getSelection();
highlight_text(sel);
}
.hlt {
background: yellow;
}
<div class="highlight">
<p>
Lorem ipsum dolor sit amet, zril accusata postulant at ius. Dicat etiam luptatum ea pri. Duo docendi vulputate dissentiet ut, tollit bonorum duo eu. Maiorum adolescens scriptorem usu eu, sit idque facer causae ei. Choro nostrum at pro, sumo essent suscipiantur pri ex. Quo case veritus definiebas eu, sit postulant dissentias ei.<br>
<br>
Mel cu porro decore, cum et simul recteque inciderint. His ne omnes sententiae, ut omittantur dissentiet accommodare sed. Pro minim necessitatibus ne, no malis integre quo. Sed utroque molestiae interpretaris ne. Oportere indoctum at has, te sale semper eum, ea nam vitae dissentiet.
</p>
</div>