我需要能够在元素中加粗文本(它不需要与pre一起使用,但我希望可以)。
例如:
这是我希望显示的字符串。
是否有能力完全在带有索引的html和css中做到这一点,那我该怎么办?还是我应该使用其他东西?
编辑:文本是动态的。粗体位置将用*指定
最佳答案
长话短说,据我所知,CSS无法仅凭文本选择文本。因此,您将需要使用javascript来实现所追求的目标。
您可以使用replace()
// check all elments with given class
[...document.querySelectorAll('.check-those-p-tags')].forEach(function(element){
// iterate over all elements
var resultString = element.innerHTML.replace(
/the/g, // search for all (g = global) "the" in the innerHTML
'<span class="alert">$&</span>' // replace/wrap the "the" with some tags and class
// "$&" means => Inserts the matched substring.
);
element.innerHTML = resultString; // overwrite the innerHTML with the new string
});
.alert { color: red; font-weight: bold; }
<p class="check-those-p-tags">This is the string i wish to display.</p>
您也几乎可以写成一行
[...document.querySelectorAll('.check-those-p-tags')].forEach(function(element){
element.innerHTML = element.innerHTML.replace(/the/g, '<span class="alert">$&</span>');
});
.alert { color: red; font-weight: bold; }
<p class="check-those-p-tags">This is the string i wish to display.</p>
关于html - 如何通过特定索引设置文本样式?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58364187/