|
|

楼主 |
发表于 2023-7-9 09:02
|
显示全部楼层
二楼代码
- <style>
- #mydiv {
- margin: 20px auto;
- width: 740px;
- height: 400px;
- border: 1px solid purple;
- background: linear-gradient(to right top,antiquewhite,purple);
- position: relative;
- }
- li-zi {
- position: absolute;
- border-radius: 50%;
- clip-path: polygon(100% 0%, 0% 0%, 0% 100%, 100% 100%, 100% 50%, 95% 50%, 27.5% 88.97%, 27.5% 11.03%, 95% 50%, 100% 50%, 100% 0%);
- animation: rot 6s infinite linear;
- }
- @keyframes rot { to { transform: rotate(360deg); } }
- </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.bg = 'purple';
- 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;
- background: ${this.bg};
- `;
- this.pa.appendChild(this.ele);
- this.moving();
- }
- //移动粒子
- moving() {
- if(canMove) {
- this.left += this.xstep;
- this.top += this.ystep;
- if(this.left <= 0 || this.left >= this.pa.offsetWidth - this.size) this.xstep = -this.xstep;
- if(this.top <= 0 || this.top >= this.pa.offsetHeight - this.size) this.ystep = -this.ystep;
- this.ele.style.left = this.left + 'px';
- this.ele.style.top = this.top + 'px';
- }
- requestAnimationFrame(this.moving.bind(this));
- }
- }
- let stepAr = [0.5,-0.5,1,-1,0.8,-0.8,1.2,-1.2]; //步幅数组
- //实例化 Lizi
- Array.from({length: 30}).forEach((element) => {
- let xIdx = Math.floor(Math.random() * stepAr.length),
- yIdx = Math.floor(Math.random() * stepAr.length);
- element = new Lizi(mydiv);
- element.size = 10 + Math.ceil(Math.random() * 20);
- element.left = Math.floor(Math.random() * (mydiv.offsetWidth - element.size));
- element.top = Math.floor(Math.random() * (mydiv.offsetHeight - element.size));
- element.xstep = stepAr[xIdx];
- element.ystep = stepAr[yIdx];
- element.bg = '#' + Math.random().toString(16).substr(-6);
- element.creating();
- });
- mydiv.onclick = () => canMove = !canMove; // 宿主元素单击事件 :粒子运动/暂停
- </script>
复制代码
|
|