Text highlighting based on positions

和自甴很熟 提交于 2019-12-25 06:46:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!