哪个更快? - 修改css属性或在jquery中添加类 [英] Which is faster? - modifying css property or adding class in jquery
问题描述
我有大约100个元素,我正在尝试使用jquery创建动画。
I have about 100 elements in like and am trying to create an animation with jquery.
<div class="box" id="a1"></div>
我需要根据函数为每个元素添加特殊样式。
I need to add special styles to each of the elements based on a function.
其中哪一个在浏览器中呈现得更快:
which of them is rendered faster in browser:
添加css属性
$(this).css({'background-color':'#000'})
或添加类
$(this).addClass("style1")
已更新
我想添加更多内容:
Updated Few more things i wish to add:
- 现在它有100个元素,我正在通过jquery添加它们。
- 要创建随机性,我需要创建大约25种样式 - 我正在通过javascript实现
- 我也应该将样式表的大小添加到相同内容以获得准确的基准。
推荐答案
根据 jsPerf ,addClass显而易见加快了约50%。
According to jsPerf, addClass is noticeably faster by about 50%.
这是Chrome的jsPerf数据,但是我的测试使用Firefox大致相同:
Here's the jsPerf data for Chrome but in my tests it was about the same using Firefox:
$('#a1')。css({'background-color':'# 000'})
82,043±0.21%48%
较慢
$('#a1').css({ 'background-color': '#000' })
82,043 ±0.21% 48%
slower
$('#a1') .addClass(style1)
最快158,876±0.83%
$('#a1').addClass("style1")
158,876 ±0.83% fastest
这篇关于哪个更快? - 修改css属性或在jquery中添加类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!