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

如何使用JavaScript向同一HTML文件中添加指定CSS样式?

实现方法

最简单的方式是通过JS动态创建style标签插入页面,即可让样式生效,完整代码如下:

// 创建style元素
const customStyle = document.createElement('style');
// 写入CSS内容
customStyle.textContent = `
body {
    font-family: Verdana, Geneva, Tahoma, sans-serif;
    font-size: 1.6rem;
    padding: 1rem;
}

ul {
    list-style-type: disc;
    padding: 1rem 1rem 1rem 4rem;
    line-height: 1.5; /* 原代码中list-style: 1.5为无效属性,已修正为行高设置,可按需调整 */
    list-style-position: inside;
}

h1 {
    font-size: 24px;
    color: rgb(247, 34, 211);
    padding-bottom: 2rem;
}

h2 {
    font-size: 2.4rem;
    margin-bottom: 1rem;
}
`;
// 插入到页面头部使样式生效
document.head.appendChild(customStyle);

使用说明

将上述代码包裹在<script>标签内,放入你的HTML文件中即可,推荐放在</body>闭合标签之前,页面加载时会自动插入样式。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 16:54:05