javascript - 将基于 Javascript 的背景动画限制为某些特定的 Div
问题描述
我一直在尝试使用动画背景,使用在此链接上找到的 Javascript:https ://codepen.io/nashvail/pen/wpGgXO
它工作正常。但问题是,一旦实施,就会满屏。
我希望动画位于我网页的某些特定 DIV 元素中。
帮帮我。
// Some random colors
const colors = ["#3CC157", "#2AA7FF", "#1B1B1B", "#FCBC0F", "#F85F36"];
const numBalls = 50;
const balls = [];
for (let i = 0; i < numBalls; i++) {
let ball = document.createElement("div");
ball.classList.add("ball");
ball.style.background = colors[Math.floor(Math.random() * colors.length)];
ball.style.left = `${Math.floor(Math.random() * 100)}vw`;
ball.style.top = `${Math.floor(Math.random() * 100)}vh`;
ball.style.transform = `scale(${Math.random()})`;
ball.style.width = `${Math.random()}em`;
ball.style.height = ball.style.width;
balls.push(ball);
document.body.append(ball);
}
// Keyframes
balls.forEach((el, i, ra) => {
let to = {
x: Math.random() * (i % 2 === 0 ? -11 : 11),
y: Math.random() * 12
};
let anim = el.animate(
[
{ transform: "translate(0, 0)" },
{ transform: `translate(${to.x}rem, ${to.y}rem)` }
],
{
duration: (Math.random() + 1) * 2000, // random duration
direction: "alternate",
fill: "both",
iterations: Infinity,
easing: "ease-in-out"
}
);
});
.ball {
position: absolute;
border-radius: 100%;
opacity: 0.7;
}
<div class="ball">
</div>
解决方案
像这样?
// Some random colors
const colors = ["#3CC157", "#2AA7FF", "#1B1B1B", "#FCBC0F", "#F85F36"];
const numBalls = 50;
const balls = [];
for (let i = 0; i < numBalls; i++) {
let ball = document.createElement("div");
ball.classList.add("ball");
ball.style.background = colors[Math.floor(Math.random() * colors.length)];
ball.style.left = `${Math.floor(Math.random() * 100)}%`;
ball.style.top = `${Math.floor(Math.random() * 100)}%`;
ball.style.transform = `scale(${Math.random()})`;
ball.style.width = `${Math.random()}em`;
ball.style.height = ball.style.width;
balls.push(ball);
document.getElementById("box").append(ball);
}
// Keyframes
balls.forEach((el, i, ra) => {
let to = {
x: Math.random() * (i % 2 === 0 ? -11 : 11),
y: Math.random() * 12
};
let anim = el.animate(
[
{ transform: "translate(0, 0)" },
{ transform: `translate(${to.x}rem, ${to.y}rem)` }
],
{
duration: (Math.random() + 1) * 2000, // random duration
direction: "alternate",
fill: "both",
iterations: Infinity,
easing: "ease-in-out"
}
);
});
.ball {
position: absolute;
border-radius: 100%;
opacity: 0.7;
}
#box{
width: 300px;
height: 300px;
border: 1px solid red;
position: relative;
overflow: hidden;
}
<div id="box"></div>
推荐阅读
- javascript - 如何在反应中使用 howler.js?
- scheduling - 使用间隔进行调度时如何在 CP 中获取当前时间
- reactjs - React Native - Tipsi-stripe 错误 - '无法读取未定义的属性'init''
- c++ - 变量只能全局“声明”,不能修改/(单独初始化)
- c# - 使用带有 x509 证书的 IIS 托管 WCF 服务进行身份验证
- python - 如何在 Python 中为 Google Analytics Reporting API(REST 方法)获取 oauth2-token
- angular - 无法绑定到“主题”,因为它不是“jqxTree”的已知属性
- c++ - C++ 应用程序:清除命令行参数?
- javascript - php 数据库到 javascript 图表
- angular - 带有 HashRouter 的子路径上的 Angular 6 无法加载图像资产