我想使用 jQuery 在网页上某个值的索引处突出显示字符串的字符。该值是可变的——一次位于索引 2,下一次位于索引 3。
var copy = "I am learning how to program.";
$('#letter').text(copy);
//code to highlight
输出示例:
我想使用 jQuery 在网页上某个值的索引处突出显示字符串的字符
要按索引突出显示字符,请使用以下代码片段。这适用于已经生成的 DOM。要使其正常工作,您所需要的只是一个索引。
$(function() {
var docText = $('#docContent').text();
var modifiedText = docText.highLightAt(7); //pass a index and that text will be highlighted.
$('#docContent').html(modifiedText);
//you can replace this 3 lines of code to single line like
// $('#docContent').html($('#docContent').text().highLightAt(7));
});
//define a highLightAt function to replace your char with a highlighted one.
String.prototype.highLightAt = function(index) {
return this.substr(0, index) + '<span class="highlight">' + this.substr(index,1) + '</span>' + this.substr(index +1);
}
.highlight {
background-color: yellow;
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="docContent">
You random text goes here, And The program would highlight that particular character at a given index.
</div>
Note:
我不知道如何让索引突出显示,您可能最终会给出空格字符的索引,或者您可能无法完全控制索引,除非您非常确定如何生成它。所以我觉得玩角色应该更容易、更安全。
附加信息
之前我曾为 SO 中的一个人构建过类似的东西。这里是工作中的小提琴 https://jsfiddle.net/RajReddy/y6sur9h8/。这必须给你一个基本的想法。下面是一个片段,有兴趣的话可以看一下。
$(function(){
var docText = $('#docContent')[0].innerHTML;
var modifiedText = docText.replace(/e/g, "<span class='highlight'>e</span>"); //using regex to match all the chars `e`, We are not playing with the index, But only chars here
$('#docContent').html(modifiedText);
setInterval(function() {
$('span.highlight:not(.highlight-active):eq(0)').addClass('highlight-active');
}, 1000);
});
.highlight-active {
background-color: yellow;
color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="docContent">
You random text goes here, And The program would highlight all the characters 'e' in this text.
</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)