如何创建背景层无模糊彩色浮动圆形元素?前端新手求助
实现彩色圆形底层背景的简单方案
直接给你一套新手友好的实现代码,注释都写清楚了,你可以直接用:
1. HTML结构
先加一个背景容器,用来放所有圆形,确保它在页面最底层:
<!-- 背景容器,放在body最前面 --> <div class="circle-bg"></div> <!-- 你的其他页面内容,示例内容可替换 --> <div class="content"> <h1>你的页面内容</h1> <p>这些内容会显示在圆形背景的上方</p> </div>
2. CSS样式
设置背景容器的层级和布局,以及圆形的基础样式:
/* 背景容器:占满整个视口,固定在最底层 */ .circle-bg { position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; z-index: -1; /* 确保在所有元素后面 */ overflow: hidden; /* 隐藏超出视口的圆形 */ } /* 圆形的基础样式 */ .circle-bg .circle { position: absolute; border-radius: 50%; opacity: 0.7; /* 可选:调整透明度让圆形叠加更自然 */ } /* 示例内容样式,可替换为自己的样式 */ .content { padding: 2rem; font-family: sans-serif; }
3. JavaScript逻辑
动态生成圆形,并且让它们缓慢移动:
const bgContainer = document.querySelector('.circle-bg'); // 自定义圆形颜色集合 const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#FFA07A', '#98D8C8', '#F7DC6F', '#BB8FCE']; // 要生成的圆形数量 const circleCount = 15; // 创建单个圆形的函数 function createCircle() { const circle = document.createElement('div'); circle.classList.add('circle'); // 随机设置圆形大小(50-200px区间) const size = Math.random() * 150 + 50; circle.style.width = `${size}px`; circle.style.height = `${size}px`; // 随机设置初始位置 circle.style.left = `${Math.random() * 100}vw`; circle.style.top = `${Math.random() * 100}vh`; // 随机选择颜色 circle.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)]; // 随机设置移动速度和方向(-0.25到0.25的速度区间) const speedX = (Math.random() - 0.5) * 0.5; const speedY = (Math.random() - 0.5) * 0.5; // 圆形移动逻辑 function moveCircle() { let currentLeft = parseFloat(circle.style.left); let currentTop = parseFloat(circle.style.top); // 更新位置 currentLeft += speedX; currentTop += speedY; // 超出视口后重置位置,实现循环移动 if (currentLeft < -size) currentLeft = 100 + size; if (currentLeft > 100 + size) currentLeft = -size; if (currentTop < -size) currentTop = 100 + size; if (currentTop > 100 + size) currentTop = -size; circle.style.left = `${currentLeft}vw`; circle.style.top = `${currentTop}vh`; // 持续调用实现流畅动画 requestAnimationFrame(moveCircle); } // 启动移动 moveCircle(); // 将圆形添加到背景容器 bgContainer.appendChild(circle); } // 批量生成圆形 for (let i = 0; i < circleCount; i++) { createCircle(); }
关键说明
z-index: -1确保背景容器在所有页面内容的后方- 用
requestAnimationFrame实现流畅的移动动画,性能比setInterval更好 - 所有参数(颜色、数量、大小、移动速度)都可以根据需求自由调整
- 代码中未添加任何模糊效果,完全符合你的要求
内容的提问来源于stack exchange,提问作者kiki
相关产品推荐
相关产品推荐

