gpt4 book ai didi

javascript - 使用 vanilla javascript,从 head 中将类添加到 body

转载 作者:行者123 更新时间:2023-11-29 10:06:46 25 4
gpt4 key购买 nike

我想在 head 中做一个快速的 javascript 检查标签,像这样:

<html>
<head>
...
<script>
document.body.classList.remove("no-js");
document.body.classList.add("js");
</script>
</head>
<body class='no-js'>
...
</body>
</html>

这行不通。 Cannot read property classList of null ,这......很公平。如果我移动 <script>标记为 <body> , 一切正常,但我想要 <script><head> 中标记.

我有哪些选择?

编辑:我应该更清楚地了解这个错误。我意识到问题是当我试图添加类时 body 没有加载。但是,我最初使用了一些 Modernizr,它能够以某种方式从头部修改 body 类,我认为它没有使用 window.onload或类似的东西。

最佳答案

加载正文后运行代码。有几种方法可以解决这个问题:

  1. 将代码移动到在全局上下文中定义的命名函数中,并在 onload 中调用它。

<html>

<head>
...
<script>
function load() {
document.body.classList.remove("no-js");
document.body.classList.add("js");
}
</script>
</head>

<body onload="load();" class='no-js'>
...
</body>

</html>

  1. 或将代码移至DOMContentLoaded事件监听器回调,以便在加载 dom 元素后调用。

<html>

<head>
...
<script>
document.addEventListener("DOMContentLoaded", function() {
document.body.classList.remove("no-js");
document.body.classList.add("js");
});
</script>
</head>

<body class='no-js'>
...
</body>

</html>

  1. 或者将整个script标签移到页面末尾。

<html>

<head>
...
</head>

<body class='no-js'>
...
<script>
document.body.classList.remove("no-js");
document.body.classList.add("js");
</script>
</body>


</html>

关于javascript - 使用 vanilla javascript,从 head 中将类添加到 body,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41845391/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com