本文主要是介绍html弹球代码,JS弹弹球,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
HtmlCssJs
* {
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) {
//生成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 <= 0) {
Left = Math.min(Left, maxLeft); //限制Left的最大值
Left = Math.max(Left, 0); //限制最小值
Ball.leftVal = -Ball.leftVal;
Ball.style.backgroundColor = randomC();
}
if (Top >= maxTop || Top <= 0) {
Ball.topVal = -Ball.topVal;
Top = Math.min(Top, maxTop); //限制Left的最大值
Top = Math.max(Top, 0); //限制最小值
Ball.style.backgroundColor = randomC();
}
Ball.style.top = Top + "px";
Ball.style.left = Left + "px";
}
requestAnimationFrame(auto)
}
// rgb(0-255)
function randomC() {
var r = Math.floor(Math.random() * 256),
g = Math.floor(Math.random() * 256),
b = Math.floor(Math.random() * 256);
return "rgb(" + r + "," + g + "," + b + ")";
}
}
↑上面代码改变,会自动显示代码结果
jQuery调用版本:2.1.4
JS弹弹球-www.sucainiu.com积分说明:注册即送15牛币,每日签到可获得5牛币,成为VIP会员可永久免牛币下载! 充值积分 充值会员 更多说明»
代码描述:根据浏览器视窗变化范围的弹弹球
球球的个数与速度在这里:
play(10);
function play(num) {
//生成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);
}
这篇关于html弹球代码,JS弹弹球的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!