Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/443.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
阻止浏览器在javascript中呈现CSS更改?_Javascript_Css_Requestanimationframe - Fatal编程技术网

阻止浏览器在javascript中呈现CSS更改?

阻止浏览器在javascript中呈现CSS更改?,javascript,css,requestanimationframe,Javascript,Css,Requestanimationframe,我需要尽快完成以下代码块: //someSpans is an array of spans, with each span containing two child spans inside of it $.each( someSpans, function (i, span) { //Get the span widths, then add them to the style to make them permanent var aSpan = span.children[

我需要尽快完成以下代码块:

//someSpans is an array of spans, with each span containing two child spans inside of it
$.each( someSpans, function (i, span) {
    //Get the span widths, then add them to the style to make them permanent
    var aSpan = span.children[0];
    var bSpan = span.children[1];
    span.style.width = (aSpan.offsetWidth + bSpan.offsetWidth) + 'px';
    aSpan.style.width = aSpan.offsetWidth + 'px';
    bSpan.style.width = bSpan.offsetWidth + 'px';
});
如果someSpans是一个包含1000个对象的数组,那么上面显示的这个循环将导致3000个浏览器重绘,即使屏幕上实际上没有任何变化,因为样式中的新“宽度”属性与现有的“自动”宽度匹配。有没有办法防止浏览器在循环完成之前重新绘制CSS?我觉得这将大大减少完成循环所需的时间

我觉得这可能是做我想做的事情的关键,但也许我做得太离谱了。

关于为什么的评论很有道理,这里有一个更好的答案

这里的部分问题是样式的交替读/写。也就是说,设置
span.style.width
现在已使
aSpan.offsetWidth
变为“脏”,并且必须呈现CSS。但是,考虑一下:

var aWidth = aSpan.offsetWidth;
var bWidth = bSpan.offsetWidth;
span.style.width = (aWidth + bWidth) + 'px';
aSpan.style.width = aWidth + 'px';
bSpan.style.width = bWidth + 'px';
渲染现在减少到每个循环一次。更具体地说,是在下一次迭代中读取
offsetWidth
导致渲染

练习:虽然它会使代码变得更迟钝,有时是不必要的,但我有时会编写这样的代码来循环两次。第一次将操作收集到一个数组中,第二次循环能够组合所有“设置”操作,而无需访问任何布局值


MSDN有一些非常好的功能,其中最适用的功能是

,可能值得一问,为什么您首先要这么做?如果性能如此重要,为什么要使用jQuery?使用纯javascript会快得多,如果您想在循环完成之前阻止浏览器呈现DOM元素,可以将其放入其中,然后将元素追加到应该添加的位置。另外,看看Yes,看看setTimeout@Givi:我只是想让你知道,我使用了另一种方法,利用DocumentFragments来大大降低操作速度。谢谢你给我指明了正确的方向!