How to realize the effect of bouncing Ball with Native js
This article mainly introduces the relevant knowledge of how to achieve the bouncing ball effect of the native js, the content is detailed and easy to understand, the operation is simple and quick, and has a certain reference value. I believe you will gain something after reading this article on how to achieve the bouncing ball effect of the native js. Let's take a look.
The effect is as follows
Source code display
Pinball (native js) * {margin:0; padding:0; font-family:Microsoft YaHei,serif;} li {list-style:none;}. Ball {position:absolute; top:0; left:0; width:100px; height:100px; background:pink; border-radius:50%;} play (10); function play (num) {/ / generate num div for (var I = 0; I)
< num; i++) { var Div = document.createElement("div"); Div.className = "ball"; Div.leftVal = 3 + i; //预存每个球的初始速度 Div.topVal = 3 + i; //预存每个球的初始速度 Div.style.backgroundColor = randomC(); document.body.appendChild(Div); } var aBall = document.querySelectorAll(".ball"); maxTop = document.documentElement.clientHeight - aBall[0].clientHeight, //获取top的最大值 maxLeft = document.documentElement.clientWidth - aBall[0].clientWidth; //获取left的最大值 _window.onresize = function() { maxTop = document.documentElement.clientHeight - aBall[0].clientHeight; //获取top的最大值 maxLeft = document.documentElement.clientWidth - aBall[0].clientWidth; // }; auto(); function auto() { for (var i = 0; i < num; i++) { var Ball = aBall[i], startL = Ball.offsetLeft, //取每个球的初始left和TOP值 startT = Ball.offsetTop, //取每个球的初始left和TOP值 Left = startL + Ball.leftVal, //改变,每个球的left和top值 Top = startT + Ball.topVal; //改变,每个球的left和top值 if (Left >= maxLeft | | Left = maxTop | | Top