我做了一个脚本,可以在页面上随机定位一些图标。当浏览器全屏打开时,这个脚本运行得很好,但如果我以最小的宽度打开它,它会使页面加载不停止,然后崩溃,尽管它在手机上运行得很好。以下是代码
function initialPosition() {
// get page dimension
const body = document.body,
html = document.documentElement,
sizewidth = window.innerWidth;
const pageHeight = Math.max(
body.scrollHeight,
body.offsetHeight,
html.clientHeight,
html.scrollHeight,
html.offsetHeight
);
const icoSize = +getComputedStyle(document.documentElement)
.getPropertyValue("--ico")
.replace(/([^\0-\9])/g, "");
const maxSpare = icoSize * 2;
const sizeheight = window.innerHeight * 2;
const distEachCol = icoSize * 8;
const distEachRow = icoSize * 4;
let icons = ``;
let currentColumn = icoSize;
let currentRow = icoSize;
const maxAnim = 10;
for (let c = 0; currentRow < sizeheight; ) {
if (currentColumn < sizewidth) {
const icoN = Math.floor(Math.random() * maxAnim) + 1;
const addToRow = Math.floor(Math.random() * maxSpare) + 1;
const addToCol = Math.floor(Math.random() * maxSpare) + 1;
icons += ``;
currentColumn += distEachCol;
} else if (currentColumn > sizewidth) {
currentColumn = icoSize;
currentRow += distEachRow;
if (c === 1) {
c = 0;
currentColumn = distEachCol * 0.5;
continue;
}
c++;
}
}
document
.querySelector(".containerico")
.insertAdjacentHTML("afterbegin", icons);
}
initialPosition();发布于 2021-02-20 10:33:24
我猜你有潜在的无限循环。
你应该检查一下iconSize大于零(否则会得到无限循环)
currentColumn可能等于sizewidth但您只选中>或<,因此您将再次得到无限循环
在这样的循环中最好有一些计数器,这样可以防止无限循环,并简化调试。我建议你写一些测试,这样你就可以很容易地检查不同的情况。
您可以使用https://codesandbox.io/s/vanilla?file=/src/index.js调试你的脚本,它内置了防止无限循环的功能。
https://stackoverflow.com/questions/66198481
复制相似问题