You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中为document.write输出的内容添加指定CSS样式

实现方案

有两种纯JavaScript实现方式,都可以满足需求:

方式1:输出带内联样式的标签

直接在document.write输出的h1标签中加入style属性,把需要的样式直接写在属性里:

document.write(`<h1 style="color: blue;font-size: 80px;font-weight: bold;text-align: center;font-family: Arial;">Elzero</h1>`);

方式2:动态注入全局样式规则

如果后续需要复用该样式,可以先通过JS创建style标签插入到页面头部,再输出h1内容:

// 注入样式规则
const styleEl = document.createElement('style')
styleEl.textContent = `
h1 {
  color: blue;
  font-size: 80px;
  font-weight: bold;
  text-align: center;
  font-family: Arial;
}
`
document.head.appendChild(styleEl)
// 输出页面内容
document.write("<h1>Elzero</h1>")

内容的提问来源于stack exchange,提问作者Mariam Kilany

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 17:27:04