JS实现随机生成球在页面弹动
Posted 何伟
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS实现随机生成球在页面弹动相关的知识,希望对你有一定的参考价值。
<body>
<div class="dian">
<input type="button" value="点我一下试试!">
</div>
<script>
let clickInput = document.querySelector("input");
let randomTop, randomLeft, vx, vy, moveDiv, timer
clickInput.addEventListener("click", () => {
moveDiv = document.createElement("div");
document.body.appendChild(moveDiv);
randomTop = parseInt(Math.random() * (innerHeight - 99));
randomLeft = parseInt(Math.random() * (innerWidth - 99));
moveDiv.style.top = randomTop + "px";
moveDiv.style.left = randomLeft + "px";
vx = 1;
vy = 1;
timer = setInterval(() => {
randomTop += vx;
randomLeft += vy;
moveDiv.style.top = randomTop + "px";
moveDiv.style.left = randomLeft + "px";
if (randomTop >= (innerHeight - 99) || randomTop <= 0) {
vx = -vx;
}
if (randomLeft >= (innerWidth - 99) || randomLeft <= 0) {
vy = -vy;
}
}
, 1)
})
</script>
</body>
以上是关于JS实现随机生成球在页面弹动的主要内容,如果未能解决你的问题,请参考以下文章