对于这个例子,在调整大小时,我需要知道如何计算一堆 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/