js实现网页回弹小球效果
2024-10-20 20:02:57
直接上效果图
运行页面会首先弹出一个输入框,询问用户想要产生的小球数量,随后后台就会产生指定数量的小球,在页面中来回跳动,触碰到页面边框时,就会回弹,且产生的小球颜色随机,小球在页面中的位置随机,小球运行的速度随机。
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>会反弹的小球</title>
<style>
* {
/*margin: 0;*/
padding: 0;
overflow: hidden;
}
span {
width: 100px;
height: 100px;
border-radius: 50%;
position: absolute;
}
</style>
</head>
<body>
</body>
</html>
<script>
/**
*效果为,页面生成用户指定数量的不同颜色的小球,然后各自移动,触碰到边界就回弹
*/
let count = parseInt(prompt("你想随机产生几个小球?"));
// console.log(count)
for (let i = 1; i <= count; i++) {
// i = document.createElement("span");
// document.body.appendChild(i);
// console.log(i)
document.body.innerHTML += `<span></span>`
}
let spans = document.getElementsByTagName('span');
for (let i = 0; i < spans.length; i++) {
spans[i].style.backgroundColor = color();
site(spans[i]);
sporting(spans[i]);
}
/**
*返回一个随机颜色
*/
function color() {
let rr = Math.round(Math.random() * 255);
let gg = Math.round(Math.random() * 255);
let bb = Math.round(Math.random() * 255);
return `rgb(${rr},${gg},${bb})`;
}
/**
*返回页面内的一个随机位置
*/
function site(now) {
let w = window.innerWidth - now.offsetWidth;
let h = window.innerHeight - now.offsetHeight;
now.style.left = `${Math.round(Math.random() * w)}px`
now.style.top = `${Math.round(Math.random() * h)}px`
}
/**
* 实现回弹效果
* @param now 传入需要回弹的对象
*/
function sporting(now) {
let x = now.offsetLeft, y = now.offsetTop;
let w = 0, h = 0;
let flagX = true;
let flagY = true;
setInterval(function () {
w = window.innerWidth - now.offsetWidth;
h = window.innerHeight - now.offsetHeight;
if (x > w) flagX = false;
if (y > h) flagY = false;
if (x < 1) flagX = true;
if (y < 1) flagY = true;
x = flagX ? ++x : --x;
y = flagY ? ++y : --y;
now.style.left = `${x}px`
now.style.top = `${y}px`
}, (Math.round(Math.random() * 10 + 1)))
}
</script>
如果对你有帮助的话,三连支持一下吧!
最新文章
- 面试准备 - 最大堆的Csharp实现
- 使用 SyndicationFeed 输出 Rss
- php CodeIgniter处理多环境错误级别配置
- LINQ 基本子句之三 let
- eval以及json
- centos安装vim7.4
- MapReduce源代码分析MapTask分析
- Jmeter察看结果树的响应数据中的中文显示乱码问题处理
- 【ASP.NET MVC 学习笔记】- 03 Razor语法
- PXE+Kickstart 全自动安装部署CentOS7.4
- [LeetCode] Design Excel Sum Formula 设计Excel表格求和公式
- Flask构建微电影(一)
- .net core 使用IIS作为宿主Web服务器,部署常见问题
- OSGi解决的问题
- [原创]networkx 画中文节点
- leetcode114
- LeetCode--003--无重复字符的最长子串(java)
- 将Delphi的对象方法设为回调函数
- P4factory ReadMe Quickstart 安装p4factory
- css属性之float
热门文章
- Unity——火烧+水波纹效果(噪音图)
- 关于 this.$route.meta.operations.includes(&#39;delete&#39;) 取不到值的问题
- webSocket 前端 js 加入 心跳机制 的基本写法
- IK 分词器
- 学习Flutter从0开始
- Linux基础之终端、控制台、tty、pty简介说明
- 【PTA】6-1 **删除C程序中的注释 (31 分)
- day 21 C语
- 1.配置桥接,并抓包验证 2.实现免密登录 3.修改登录端口: 22-》2222 4.不允许root用户远程登录 5.创建用户sshuser1,并设置密码,且只允许sshuser1远程ssh登录
- 《剑指offer》面试题56 - I. 数组中数字出现的次数