jQuery 将 css 类添加到 DOM 主体的安全且最快的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17457583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Safe AND quickest way to add a css class to the body of the DOM
提问by contactmatt
I am looking to add a class to the body element of the DOM. For something so simple, and with the body element itself loading quick (at least, I would think it would load quicker than, say, an element buried deem in the DOM), must I really wait for the jQuery Ready event to do such a simple task? I'm looking to avoid a "flicker" effect when adding the style to the body, since I'll have different CSS styles attached to this class take effect when added.
我希望向 DOM 的 body 元素添加一个类。对于如此简单的事情,并且 body 元素本身加载速度很快(至少,我认为它加载速度比说,一个埋在 DOM 中的元素要快),我真的必须等待 jQuery Ready 事件执行这样的操作吗?简单的任务?我希望在将样式添加到正文时避免“闪烁”效果,因为我将附加到此类的不同 CSS 样式在添加时生效。
I can do something like:
我可以做这样的事情:
jQuery(window.document).ready(function () {
jQuery("body").addClass("home");
});
But is there a faster, yet safe way? I don't care if its jQuery or native JavaScript
但是有没有更快但安全的方法呢?我不在乎它是 jQuery 还是原生 JavaScript
回答by
document.body.className += ' ' + 'home';
Performance comparision: className
vs classList
vs addClass
:
性能比较:className
vsclassList
vsaddClass
:
Update(based on PSL's comment)
更新(基于 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
或者对于较新的
document.body.classList.add("home");
确保您在 下执行此操作
<body>
,如果从<head>
脚本应用它将无法工作
回答by Karl-André Gagnon
Right after the opening body
tag, you can create a script tag :
在开始body
标签之后,您可以创建一个脚本标签:
<body>
<script>
$('body').addClass('home')
</script>
<!-- HTML content bellow -->
</body>
The only condition is that the jQuery is loaded in the head
.
唯一的条件是 jQuery 加载到head
.