在一个div中,如何将样式分别应用于每个字符? [英] How can I apply styles to each character separately when they are in one div?
本文介绍了在一个div中,如何将样式分别应用于每个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想为我的一个div的每个字母提供不同的背景CSS样式,例如:
I want to give a different background CSS style per letter for one of my divs, e.g.:
<div class="hello">1999</div>
因此每个单词后面都有一个类似计数器的背景.供参考:
so there is a counter-like background behind every word. For reference:
如何做到这一点而又不将div类一一分开?
How can I do that without separating the div classes one by one?
推荐答案
如果要在页面加载后执行此操作,则可以使用JavaScript
If you want to do this after the page loads, you can use JavaScript
类似这样的东西
const div = document.querySelector(".hello")
div.innerHTML = div.textContent.split("").map(letter => `<span ${letter.trim() === "" ? "" : 'class="block"'}>${letter}</span>`).join("")
.block {
display: inline-block;
height: 50px;
width: 50px;
background-color: black;
color: white;
margin: 2px;
font-size: 34px;
text-align: center;
vertical-align: middle;
line-height: 50px;
font-family: arial, sans-serif;
}
<div class="hello"> 1999 </div>
表情符号:
.hello { font-size: 50px; letter-spacing: 5px;}
<div class="hello">1️⃣9️⃣9️⃣9️⃣</div>
这篇关于在一个div中,如何将样式分别应用于每个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文