在您可以在下面运行的演示中,我生成了具有随机位置和大小的圆圈。
我将页面设置为在您调整窗口大小时重新加载,但这不是我想要的。 我想在调整窗口大小时重新计算圆圈的大小和位置,而不重新加载页面。
我尝试了很多东西,但我就是无法让它工作。任何帮助将不胜感激。
// 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
}
最佳答案
使用 vh 或 vw ov vmax 或 vmin 单位代替 px
这里有一些解释https://web-design-weekly.com/2014-11-18-viewport-units-vw-vh-vmin-vmax/
vw: 1/100th viewport width
vh: 1/100th viewport height
vmin: 1/100th of the smallest side
vmax: 1/100th of the largest side
// 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) / 150) // tune this to your needs
const maxSize = Math.round((viewportWidth + viewportHeight) / 80)// tune this to your needs
const size = random(minSize, maxSize)
Object.assign(circle.style, {
width: `${size}vmin`,// vmin used instead px , but vh,vw aand vmax is also avalaible
height: `${size}vmin`,// vmin used instead px , but vh,vw aand vmax is also avalaible
left: `${random(0, 100)}%`,
top: `${random(0, 100)}%`
})
return circle
})
document.body.append(...elements)
body { overflow: hidden }
span {
background: black;
position: absolute;
border-radius: 50%;
opacity: .5
}
关于javascript - 在窗口调整大小时计算圆圈的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59069910/