问题
I have some div with text and spans (include text). How I can highlight text into div if I know highlight positions? I mean:
<div>Lorem<span> ipsum</span> dolor amet</div>
for positions 2 and 14:
<div>Lo<b>rem<span> ipsum</span> dol</b>or amet</div>
I can do this simple? With small and clean code. Thank you
回答1:
HTML
<div id='mydiv'>Lorem<span> ipsum</span> dolor amet</div>
JS/Jquery
var elm = $('#mydiv');
highlite(elm, 2, 28); //specify the start and end position
// if you know the word you can find the index of word using indexOf/lastIndexOf
function highlite(element, startpos, endpos) {
var rgxp = elm.html().substr(startpos,endpos)
var repl = '<span class="myClass">' + rgxp + '</span>';
elm.html(elm.html().replace(rgxp, repl));
}
Demo
http://jsfiddle.net/raunakkathuria/sD2pX/
来源:https://stackoverflow.com/questions/20751664/text-highlighting-based-on-positions