分配的值是无效的,因此由于流氓而被忽略
;
单元之后:
Math.round((Math.random())*100)+"vh;";
请注意,您正在修改
style
其在模板中也具有插值。如果这些值是动态的,则脚本中的更改可能会被覆盖。
通常,不建议直接操作DOM。
相反,我会存储一个数组
{ x, y }
对象,并在模板中插入这些对象。在脚本中,您只需更改
数据
.
<script lang="ts">
const ballAmount = 15;
let bubbles = randomLocations();
setInterval(() => bubbles = randomLocations(), 1000);
function randomLocations() {
return Array.from({ length: ballAmount }, () => ({
x: Math.round(Math.random() * 100) + "vw",
y: Math.round(Math.random() * 100) + "vh",
}));
}
</script>
<div class="circles">
{#each bubbles as { x, y }}
<div class="bubble"
style="
width: {Math.random() * 25}vw;
opacity: {Math.random() * 0.1};
top: {y};
left: {x};
"></div>
{/each}
</div>
(通常应在卸载/销毁组件时清理超时和间隔,以避免泄漏。为简洁起见,在代码示例中跳过了这一点。)
REPL