我想通过javascript函数突出显示div中的文本,该函数将startindex和endindex作为参数。
注意:每次调用该函数时,必须清除上一个突出显示。
我以某种方式做了这个
HTML CODE
<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);
}
尽量帮助我。
答案 0 :(得分:2)
试试这个:当您再次替换所有内容时,您不需要删除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
}
<强> Demo 强>
答案 1 :(得分:0)
试试这个Fiddle
新行应该是这样的 -
var newLine = line.substring(0,start) + "<span class='highLight'>" +
line.substring(start,end) + "</span>"
+ line.substring(end,line.length);