突出显示div中的文本

普拉蒂克·鲍尔(Pratik Bhoir)

我想通过javascript函数(以startindex和endindex为参数)突出显示div中的文本。

注意:每次我调用该函数时,必须清除以前的突出显示。

我以某种方式做到了

HTML代码

<div id="readPara">Sounds good, eh? So good that the ASP.NET team decided to incorporate the provider model for authentication (membership), roles, user profile, session and other aspects of the runtime into the ASP.NET 2.0 release in 2005. To capitalize on the provider model several new controls were added such as the CreateUserWizard, Login, ResetPassword and ChangePassword controls. These controls, given the provider model, could implement these features without knowing the details of the database being used.</div>

JavaScript代码

function highlightWord(start,end){   
    $('.highLight').removeClass();
    var line = $('#readPara').text();
    console.log(line);
    if(end>line.length){
         end = line.length;   
    }   
    var newLine = line.substring(0,start) + "<span class='highLight'>" + line.substring(start,end) + "</span>" + line.substring(end,line.length);
    console.length(newLine);
    $('#readPara').contents().replaceWith(newLine);

}

尝试帮助我。

布山·卡瓦德卡(Bhushan Kawadkar)

尝试以下操作:您无需删除highLight跨度,因为您可以再次替换所有内容。并替换html,它将span作为html元素。

function highlightWord(start,end){   
    var line = $('#readPara').text();
    console.log(line);
    if(end>line.length){
         end = line.length;   
    }   
    var newLine = line.substring(0,start) + "<span class='highLight'>" +
                  line.substring(start,end) + "</span>" 
                 + line.substring(end,line.length);
    console.log(newLine);
    $('#readPara').html(newLine);// replace newline here
}

演示版

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章