将css类添加到DOM主体的安全且最快捷的方法 [英] Safe AND quickest way to add a css class to the body of the DOM
问题描述
我希望在DOM的body元素中添加一个类。对于这么简单的东西,并且body元素本身加载速度很快(至少,我认为它会加载比DOM中埋藏的元素更快),我必须真的等待jQuery Ready事件做这样的事情简单的任务?我希望在将样式添加到正文时避免闪烁效果,因为我将添加不同的CSS样式,这个类在添加时生效。
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.
我可以这样做:
jQuery(window.document).ready(function () {
jQuery("body").addClass("home");
});
但有更快,更安全的方式吗?我不在乎它的jQuery或原生JavaScript
But is there a faster, yet safe way? I don't care if its jQuery or native JavaScript
推荐答案
document.body.className += ' ' + 'home';
性能比较 : className
vs classList
vs addClass
:
Performance comparision: className
vs classList
vs addClass
:
更新(根据PSL的评论)
Update(based on PSL's comment)
或更新的
document.body.classList.add(home);
这篇关于将css类添加到DOM主体的安全且最快捷的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!