<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
body{
background-color: pink;
}
div{
position: absolute;
top:100px;
left:100px;
width: 50px;
height: 50px;
background: radial-gradient(white 0%, red 100%);
border-radius: 50%;
}
</style>
</head>
<body>
<div></div>
<script>
// 获取元素
var oDiv = document.getElementsByTagName('div')[0];
// 定义浏览器宽高
var h, w;
// 浏览器宽高发生变化时执行onresize
window.onresize = (function s() {
// 实际宽高需要减去小球的半径,否则小球会超过浏览器边缘后才反弹
w = window.innerWidth - oDiv.clientWidth;
h = window.innerHeight - oDiv.clientHeight;
return s;
})();
// 定义小球速度
var vx = 3;
var vy = 3;
// 距定位父级距离
var Lx, Ly;
function ani(){
// 距浏览器边缘距离
Lx = oDiv.offsetLeft + vx;
Ly = oDiv.offsetTop + vy;
// 如果距浏览器左侧距离超过浏览器宽度,重新赋值(左边距=浏览器宽; x方向速度取反)
if(Lx>w){
Lx = w;
vx = -vx;
}
if(Lx<=0){
Lx = 0;
vx = -vx;
}
if(Ly>h){
Ly = h;
vy = -vy;
}
if(Ly<0){
Ly = 0;
vy = -vy;
}
碰撞小球
最新推荐文章于 2024-06-18 16:25:13 发布