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

为何在body标签使用onload事件时CSS未正常渲染?

问题原因

核心问题出在document.write()的使用逻辑上:
当页面加载完成(onload事件触发)后调用document.write(),它会直接清空当前页面的所有原有内容——包括<head>里的CSS引用、整个DOM结构,然后重新写入你指定的内容。这就导致原来的CSS样式表被彻底移除,新写入的<h1>自然没有样式可应用。

解决办法

方法1:用DOM操作替代document.write()(推荐)

不要直接覆盖整个页面,而是向已存在的<body>里添加内容,这样原有页面的CSS和DOM结构都会保留:

function myFunction(){
    const heading = document.createElement('h1');
    heading.textContent = 'Have good day';
    document.body.appendChild(heading);
}

方法2:若必须用document.write()(不推荐)

如果一定要用这个方法,需要在写入的内容里重新引入CSS样式表,让新页面能加载到样式:

function myFunction(){
    document.write(`
        <link rel="stylesheet" type="text/css" href="styles.css" />
        <h1> Have good day</h1>
    `);
}

但这种方式会完全替换原有页面,所有之前加载的资源都会被丢弃,只保留新写入的内容,一般不建议这么做。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 10:18:25