3 回答

TA貢獻1804條經驗 獲得超2個贊
似乎問題在于它附加了更多i標簽或stars在調整大小時,而不是真正的 CSS 問題。
我建議#header在添加更多<i>s 之前清除包裝器。
你可以這樣做:
window.onresize = function() {
skyCity();
};
function skyCity() {
var header = document.getElementById("header")
header.innerHTML=''
for( var i=0; i < 400; i++) {
var cityLight = document.createElement("i"),
x = Math.floor(Math.random() * window.innerWidth * .98),
y = Math.floor(Math.random() * window.innerHeight),
size = Math.random() * 1.5;
animate = Math.random() * 50;
cityLight.style.left = x + 'px';
cityLight.style.top = y + 'px';
cityLight.style.width = size + 1.5 + 'px';
cityLight.style.height = size + 1.5 + 'px';
cityLight.style.opacity = Math.random();
cityLight.style.animationDuration = 10 + animate + 's';
header.appendChild(cityLight);
}
};
skyCity();
#header {display: grid;background-color: #2e2e2e;width: 100vw;height: 100vh;overflow: hidden;}
#header i {position: absolute;border-radius: 100%;background: grey; }
<div id="header"></div>
您可以查看完整頁面鏈接,以便嘗試調整窗口大小

TA貢獻2021條經驗 獲得超8個贊
簡單地說,每次調整大小時,都會調用skyCity()
400header.appendChild(cityLight);
次。它只是被編程來添加新的燈......
您可以,a)在循環之前<i>
從#header
in 中刪除每個,skyCity()
和b),b更好,<i>
在加載時初始化400,然后在調整大小時更新它們的屬性。

TA貢獻1789條經驗 獲得超8個贊
我建議您將“星”保留為數組(cityLights在下面的代碼中),并在每次瀏覽器大小更改時應用新樣式。
<style>
body, html {margin: 0;}
#header {display: grid;background-color: #2e2e2e;width: 100vw;height: 100vh;overflow: hidden;}
#header i {position: absolute;border-radius: 100%;background: grey; }
</style>
<body>
<div id="header"></div>
<script>
window.onresize = function() {
skyCity();
};
var header = document.getElementById("header");
var cityLights = []
for( var i=0; i < 400; i++) {
cityLights.push(document.createElement("i"));
}
function skyCity() {
for( var i=0; i < 400; i++) {
var cityLight = cityLights[i],
x = Math.floor(Math.random() * window.innerWidth * .98),
y = Math.floor(Math.random() * window.innerHeight),
size = Math.random() * 1.5;
animate = Math.random() * 50;
cityLight.style.left = x + 'px';
cityLight.style.top = y + 'px';
cityLight.style.width = size + 1.5 + 'px';
cityLight.style.height = size + 1.5 + 'px';
cityLight.style.opacity = Math.random();
cityLight.style.animationDuration = 10 + animate + 's';
header.appendChild(cityLight);
}
};
skyCity();
</script>
</body>
添加回答
舉報