繁体   English   中英

突出显示div中的文本

[英]highlight text in div

我想通过javascript函数突出显示div中的文本,该函数将startindex和endindex作为参数。

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

我以某种方式做到了

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);

}

尝试帮助我。

尝试以下操作:在再次替换所有内容时,不需要删除highLight span。 并替换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
}

演示版

试试这个小提琴

新行应如下所示:

var newLine = line.substring(0,start) + "<span class='highLight'>" +
              line.substring(start,end) + "</span>" 
             + line.substring(end,line.length);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM