【发布时间】:2023-03-04 00:28:01
【问题描述】:
在您可以在下面运行的演示中,我生成了具有随机位置和大小的圆圈。
我将页面设置为在您调整窗口大小时重新加载,但这不是我想要的。 我想在调整窗口大小时重新计算圆圈的大小和位置,而不重新加载页面。
我尝试了很多东西,但我就是无法让它发挥作用。任何帮助将不胜感激。
// Draw circles
const list = (length, callback) =>
Array.from(new Array(length), (hole, index) => callback(index))
const random = (min, max) => Math.random() * (max - min) + min
const viewportWidth = Math.max(
document.documentElement.clientWidth,
window.innerWidth || 0
)
const viewportHeight = Math.max(
document.documentElement.clientHeight,
window.innerHeight || 0
)
const elements = list(48, () => {
const circle = document.createElement("span")
const minSize = Math.round((viewportWidth + viewportHeight) / 48)
const maxSize = Math.round((viewportWidth + viewportHeight) / 24)
const size = random(minSize, maxSize)
Object.assign(circle.style, {
width: `${size}px`,
height: `${size}px`,
left: `${random(0, 100)}%`,
top: `${random(0, 100)}%`
})
return circle
})
document.body.append(...elements)
// Reload page on window resize
window.addEventListener("resize", () => {
window.location.reload(true)
})
body { overflow: hidden }
span {
background: black;
position: absolute;
border-radius: 50%;
opacity: .5
}
【问题讨论】:
-
将生成和“打印”圆圈的代码放入函数中并调用它,而不是在
resizeo.O 上重新加载页面 -
@Andreas 您能否将解决方案发布为答案,以便我投票并接受它?谢谢。
-
随意添加它作为自己的答案。恕我直言,这更像是一个关闭广泛的理由。
-
代替 px,使用 vh 或 vw ov vmax 或 vmin 单位
标签: javascript css ecmascript-6 window-resize