今天跟大家分享一个小球触碰到页面边缘自动反弹的小动画
<style>
* {
margin: 0;
padding: 0;
overflow: hidden;
}
div {
width: 100px;
height: 100px;
border-radius: 50%;
position: absolute;
}
</style>
</head>
<body></body>
<script>
//创建一个随机位置的球,并且出现随机的颜色
let num = parseInt(prompt("你想要出现多少个球?"));
let winHeight = window.innerHeight; //页面的可视高度
let winWidth = window.innerWidth; //页面的可视宽度
for (let i = 0; i < num; i++) {
function qiu() {
var DIV = document.createElement("div"); //创建div
let boDy = document.querySelector("body"); //引入body
boDy.appendChild(DIV); //将新创建的div添加到body中
let Hmax = winHeight - DIV.offsetHeight; //获取到能创建div的最大高度
let Wmax = winWidth - DIV.offsetWidth; //获取到能创建div的最大宽度
let nowHieght = Math.floor(Math.random() * Hmax);
let nowWidth = Math.floor(Math.random() * Wmax);
DIV.style.top = nowHieght + "px"; //设置div距离页面顶部的随机位置
DIV.style.left = nowWidth + "px"; //设置div距离页面左侧的随机位置
//制作div的随机背景颜色
function rgb() {
let r = Math.floor(Math.random() * 256);
let g = Math.floor(Math.random() * 256);
let b = Math.floor(Math.random() * 256);
return `rgb(${r},${g},${b})`;
}
DIV.style.backgroundColor = rgb();
//让div能够动起来
let H = nowHieght;
let W = nowWidth;
let emp0 = Num(5, 1);
let emp1 = Num(5, 1);
function Num(max, min) {
let shu = Math.floor(Math.random() * (max - min + 1) + min);
return shu;
}
setInterval(function () {
H += emp0;
W += emp1;
if (H <= 0 || H >= Hmax) {
emp0 = emp0 * -1;
}
if (W <= 0 || W >= Wmax) {
emp1 = emp1 * -1;
}
DIV.style.top = H + "px";
DIV.style.left = W + "px";
}, 10);
}
qiu();
}
</script>