gpt4 book ai didi

JavaScript/jQuery getSelection 高亮合并span html元素

转载 作者:行者123 更新时间:2023-11-29 15:26:38 24 4
gpt4 key购买 nike

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>

单词“Lorem”的类名“hlt”已被突出显示。我想要的是:如果我想突出显示另一个文本,包括单词“Lorem”,w/c 已经被突出显示。我想合并他们的 span html 元素。示例:如果我突出显示“Lorem”一词旁边的“ipsum”并且我还包括“Lorem”,结果将是 Lorem Ipsum。有人能帮我吗?谢谢你。

最佳答案

这个怎么样?

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>

关于JavaScript/jQuery getSelection 高亮合并span html元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38650124/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com