如何使用 spam class 更改字符串中特定文本的颜色
支付小周
结论
应该使用 HTML 的 <span> 标签,而不是 spam class。用 <span> 包裹账号,再通过 CSS 设置颜色。
Please, use the means of payment of the Credit Bank that most suits you.
Box Office, Transfer, Cashier or BCP Agent, to make payment to account
<span class="account-number">0102-0228345543469</span> Pympack SAC
.account-number {
color: red;
}
完整示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
.account-number {
color: #d32f2f;
font-weight: bold;
}
</style>
</head>
<body>
<p>
Please, use the means of payment of the Credit Bank that most suits you.
Box Office, Transfer, Cashier or BCP Agent, to make payment to account
<span class="account-number">0102-0228345543469</span>
Pympack SAC
</p>
</body>
</html>
如果内容保存在 JavaScript 字符串中
可以直接在字符串中写入 <span>:
const message = `
Please, use the means of payment of the Credit Bank that most suits you.
Box Office, Transfer, Cashier or BCP Agent, to make payment to account
<span class="account-number">0102-0228345543469</span>
Pympack SAC
`;
document.getElementById("message").innerHTML = message;
<div id="message"></div>
.account-number {
color: red;
}
这里需要使用 innerHTML。如果改用 textContent 或 innerText,浏览器会把 <span> 作为普通文本显示,样式不会生效。
动态替换指定文本
如果不能直接修改原始字符串,可以用 replace() 为账号添加 <span>:
const account = "0102-0228345543469";
const originalText = `
Please, use the means of payment of the Credit Bank that most suits you.
Box Office, Transfer, Cashier or BCP Agent, to make payment to account
0102-0228345543469 Pympack SAC
`;
const formattedText = originalText.replace(
account,
`<span class="account-number">${account}</span>`
);
document.getElementById("message").innerHTML = formattedText;
注意事项
- 正确的标签是
<span>,不是<spam>。 \n在普通 HTML 中通常不会显示为换行。如果需要保留字符串中的换行,可以添加以下样式:
#message {
white-space: pre-line;
}
- 如果字符串来自用户输入或外部接口,不要在未经处理的情况下直接赋给
innerHTML,否则可能引发 XSS 安全问题。更稳妥的方式是创建文本节点和<span>元素:
const container = document.getElementById("message");
const accountSpan = document.createElement("span");
container.append(
"Please, use the means of payment to make payment to account "
);
accountSpan.className = "account-number";
accountSpan.textContent = "0102-0228345543469";
container.append(accountSpan, " Pympack SAC");
如果当前环境不是浏览器 HTML,而是 Android、Flutter、React Native 等框架,普通 <span> 不一定能被解析,需要使用相应框架提供的富文本组件。
备注:内容仅供参考。
