javascript - 在调整大小时优化计算多个 div 宽度的最佳方法是什么?

标签 javascript jquery performance resize

对于这个例子,在调整大小时,我需要知道如何计算一堆 div 的宽度。

我想以最绝对高效的方式做到这一点。想象一个极端的例子,页面上只有 10 个 div 到 10,000 个 div。

这是该问题的 jQuery 基本示例:

$justABunchOfParentDivs = $('.class-matching-500-elements-on-a-page');
$(window).resize(function() {

    $justABunchOfParentDivs.each(function() {
        $(this).attr('data-width', $(this).width());
    });

});

我需要一个 jQuery 解决方案,但也希望看到超快的非 jQuery 解决方案。

最佳答案

要提高一点性能,您可以使用 window.requestAnimationFrame,如下所示:

$(window).resize(function() {
  window.requestAnimationFrame(function () {
    $justABunchOfParentDivs.each(function() {
            $(this).attr('data-width', $(this).width());
    });
  });
});

仅当浏览器需要时,它才会触发您的代码(对于 FPS 更好)。 此外,如果您使用标准 API 来执行此操作,它也会提高性能:

$justABunchOfParentDivs = document.querySelectorAll('.class-matching-500-elements-on-a-page');

window.onresize = function() {
  window.requestAnimationFrame(function () {
    Array.prototype.forEach.call($justABunchOfParentDivs, function(element) {
            element.setAttribute('data-width', element.offsetWidth);
    });
  });
};

关于javascript - 在调整大小时优化计算多个 div 宽度的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38754721/

相关文章:

javascript - Bootstrap 多选下拉菜单不可见

mysql - MySQL组合查询性能低下

macos - OSX WebView 非常慢且滞后

javascript - 上传文件到nodeJS服务器

javascript - 如何在发布后更改 Rails Controller 的 View ?

javascript - Extjs - 如何从 subview Controller 调用父 View Controller 方法?

javascript - 尽管设置为显示 block ,但 Bootstrap 模态未显示

javascript - jQuery 验证错误位置

javascript - 如何阻止网站在 iframe 中加载?

安卓图片加载速度