如果我给每个字符自己的#id,我就明白如何一次更改一个字符的字体样式,但是,我希望对整个网页都这样做。有没有更有效的方法?还是让数百个#ids 成为一个可行的选择?
<body>
<div>
<p> Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
</div>
<script src="jquery.js" type="text/javascript" ></script>
<script>
var text = $("p").text();
var newText = [];
for (var i = 0; i < text.length; i++) {
newText.push(text[i]);
// ???????? function goes here ????????
}
</script>
</body>
最终,我认为我需要做的是将每个字符串都变成一个 HTML 对象?这可能吗?
最佳答案
将文本转换为数组,对其进行迭代并将每个字符包装在 <span>
中- 标记并为其应用指定字体的类。
var text = $('p').text().split('');
text = text.map(function (char) {
// you probably don't want to wrap spaces
if (char === ' ') {
return char;
}
return '<span class="comicSans">'+char+'</span>';
});
// convert the array back into a string
text = text.join('');
// replace the original string with the new 'fancy' string
$('p').text(text);
样式.css
.comicSans {
font-family: "Comic Sans";
}
关于javascript - 一次改变一个字符串的字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41821232/