|
|

楼主 |
发表于 2023-7-9 11:01
|
显示全部楼层
测试代码
- <style>
- #mydiv {
- margin: 20px auto;
- width: 740px;
- height: 400px;
- background: linear-gradient(to right top,antiquewhite,black);
- overflow: hidden;
- position: relative;
- }
- li-zi {
- position: absolute;
- border-radius: 0% 100%;
- opacity: .85;
- animation: rot 3s var(--delay) infinite alternate;
- }
- @keyframes rot { to { transform: rotate(180deg); } }
- </style>
- <div id="mydiv"></div>
- <script>
- //声明粒子运动的布尔变量 :true - 可以移动;false - 不可以移动
- let canMove = true;
- //创建一个 Lizi 类
- class Lizi {
- //构造函数 : 属性设计/设置 pa - 粒子宿主元素,size - 粒子大小
- constructor(pa,size = 20) {
- this.pa = pa;
- this.size = size;
- this.left = 10;
- this.top = 10;
- this.xstep = 1; //水平移动步幅
- this.ystep = 1; //垂直移动步幅
- this.ele = document.createElement('li-zi'); //粒子标签
- }
- //创建粒子
- creating() {
- this.ele.style.cssText = `
- width: ${this.size}px;
- height: ${this.size}px;
- left: ${this.left}px;
- top: ${this.top}px;
- `;
- this.pa.appendChild(this.ele);
- this.setBg();
- this.moving();
- }
- //移动粒子
- moving() {
- if(canMove) {
- this.left += this.xstep;
- this.top += this.ystep;
- if(this.left >= this.pa.offsetWidth) {
- this.left = -this.size;
- this.setBg();
- }
- if(this.top >= this.pa.offsetHeight) {
- this.top = -this.size;
- this.setBg();
- }
- this.ele.style.left = this.left + 'px';
- this.ele.style.top = this.top + 'px';
- }
- requestAnimationFrame(this.moving.bind(this));
- }
- setBg() { this.ele.style.background = '#' + Math.random().toString(16).substring(2,8); }
- }
- let stepAr = [0.5,0.8,1,1.5]; //步幅数组
- Array.from({length: 50}).forEach((element) => {
- let yIdx = Math.floor(Math.random() * stepAr.length);
- element = new Lizi(mydiv);
- element.size = 8 + Math.ceil(Math.random() * 16);
- element.left = Math.floor(Math.random() * mydiv.offsetWidth);
- element.top = Math.floor(Math.random() * mydiv.offsetHeight);
- element.xstep = 0.2;
- element.ystep = stepAr[yIdx];
- element.bg = '#' + Math.random().toString(16).substr(-6);
- element.creating();
- element.ele.style.setProperty('--delay', Math.random() * -3 + 's');
- });
- mydiv.onclick = () => canMove = !canMove;
- </script>
复制代码
|
|