<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>
原文地址:https://www.cnblogs.com/weijiangZ/p/12116901.html