我希望将一个类添加到 DOM 的 body 元素。对于如此简单的事情,并且 body 元素本身加载速度很快(至少,我认为它加载速度比 DOM 中埋藏的元素更快),我真的必须等待 jQuery Ready 事件来执行这样的操作吗?简单的任务?我希望在将样式添加到正文时避免“闪烁”效果,因为我将附加到此类的不同 CSS 样式在添加时生效。
我可以这样做:
jQuery(window.document).ready(function () {
jQuery("body").addClass("home");
});
但是有没有更快、更安全的方法呢?我不在乎它是 jQuery 还是原生 JavaScript
最佳答案
document.body.className += ' home';
Performance comparision : className
对比classList
对比addClass
:
更新(根据 PSL 的评论)
or for newer ones
document.body.classList.add("home");
Make sure you do this under the
<body>
, it won't work if applied from a<head>
script
关于javascript - 将 css 类添加到 DOM 主体的安全且最快的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17457583/