Masonry结合AJAX加载图片时,窗口Resize触发Array.push报Invalid array length错误的求助
Masonry结合AJAX加载图片时,窗口Resize触发Array.push报Invalid array length错误的求助
我现在在做一个响应式网站,用Masonry来展示图片。网格容器里的图片项是通过AJAX请求获取填充的,这部分功能正常,但当窗口调整大小(比如切换到手机端)的时候,控制台会从masonry.js抛出错误:
masonry.pkgd.min.js:9 Uncaught RangeError: Invalid array length
at Array.push
报错指向的代码片段是:
function(t) { "use strict"; function e(t, e) { var n = t.create("masonry"); return n.prototype._resetLayout = function() { this.getSize(), this._getMeasurement("columnWidth", "outerWidth"), this._getMeasurement("gutter", "outerWidth"), this.measureColumns(); var t = this.cols; for (this.colYs = []; t--; ) this.colYs.push(0); console.log(this.colYs); this.maxY = 0 }
具体报错行就是this.colYs.push(0);这一行。
我自己的相关代码如下:
加载图片项的AJAX函数
function sendFormData() { const postData = new FormData(); // Add all selected conditions to FormData for (const [key, value] of Object.entries(selectedConditions)) { console.log("Adding to FormData:", key, value); // Debugging log if (Array.isArray(value)) { value.forEach(val => postData.append(key, val)); // If it's an array (checkboxes) } else { postData.append(key, value); // If it's a single value (radio or text input) } } fetch(BASEURL + '/search_ajax.php', { method: 'POST', body: postData }) .then(response => response.text()) // Read response as text .then(text => { console.log('Raw Response:', text); const grid = document.getElementById('grid'); grid.innerHTML = text; new AnimOnScroll(grid, { minDuration: 0.4, maxDuration: 0.7, viewportFactor: 0.2 }); // Ensure imagesLoaded only triggers after all images are loaded imagesLoaded(grid, function() { masonryInstance.reloadItems(); masonryInstance.layout(); }); }) .catch(error => { console.error('Error:', error); }); }
窗口Resize监听代码
let resizeTimeout; window.addEventListener('resize', function() { // Clear the existing timeout to avoid multiple layout recalculations clearTimeout(resizeTimeout); // Set a new timeout to delay the layout recalculation resizeTimeout = setTimeout(function() { if (masonryInstance) { masonryInstance.layout(); } }, 100); // Adjust the timeout duration as needed (in milliseconds) });
Masonry初始化代码
window.addEventListener("load", function() { const grid = document.getElementById("grid"); masonryInstance = new Masonry(grid, { itemSelector: ".grid-item", gutter: 20, transitionDuration: "2ms", isFitWidth: true, }); console.log("Masonry initialized using plain JavaScript"); });
调试发现的问题
我在报错的代码里加了console.log(this.colYs)来调试,正常加载图片项的时候,数组是正常的,比如:(3) [0, 0, 0] 0 : 281.375 1 : 334.5 2 : 182.703 length : 3,列数完全符合当前布局。但当窗口Resize的时候,数组长度会变成完全随机的数值(比如56列、65列),完全不符合当前窗口的实际情况。
我尝试在网上找相关信息,但没找到解决办法,希望有人能帮忙看看,谢谢!
备注:内容来源于stack exchange,提问作者Rosebud wells
相关产品推荐
相关产品推荐

