使用 CSS 和 HTML 的解决方案
如果要更改文本第一个单词的颜色,可以使用 CSS :before 伪元素,用于添加任何元素。
它的值由 content 属性定义。
如果不使用,则不会生成和插入内容。
在下面的示例中,我们使用带有“word”类的 <div> 元素并指定其颜色。
然后,我们将 :before 伪元素添加到“word”类中,并使用 color 属性添加要更改其颜色的单词。
之后,我们指定它的颜色。
更改文本第一个单词颜色的示例:
<!DOCTYPE html>
<html>
<head>
<title>文档的标题</title>
<style>
.word {
color: #000;
}
.word:before {
color: #f00000;
content: "Stray";
}
</style>
</head>
<body>
<div class="word">
birds of summer come to my window to sing and fly away.
And yellow leaves of autumn, which have no songs, flutter and fall there with a sign.
</div>
</body>
</html>
当然,在视觉上,我们实现了改变第一个单词颜色的目标,但这对于可访问性来说并不好。
某些屏幕阅读器可能会跳过 CSS 生成的内容。
此外,这打破了将内容与格式分开的概念。
更改第一个单词颜色的示例:
<!DOCTYPE html>
<html>
<head>
<title>文档的标题</title>
<style>
div[data-highlightword] {
position: relative;
color: #666666;
}
div[data-highlightword]::before {
content: attr(data-highlightword);
color: purple;
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div data-highlightword="Stray">
Stray birds of summer come to my window to sing and fly away.
</div>
</body>
</html>
使用 HTML <span> 标记更改第一个单词的颜色的示例:
<!DOCTYPE html>
<html>
<head>
<title>文档的标题</title>
<style>
span {
color: green;
}
</style>
</head>
<body>
<div>
<span>Example</span> for you.
</div>
</body>
</html>
日期:2020-06-02 22:15:00 来源:oir作者:oir
