我有一个具有背景渐变的 div,其值是使用 javascript 动态设置的。有时,我需要更改渐变值(可以是颜色或颜色停止位置)。我想在不使用 javascript 的情况下为这些更改设置动画(不要误会我的意思,我使用 javascript 设置了渐变值,但我想使用 CSS3 为 thise 设置动画)。我尝试像使用 CSS 一样设置 transition
属性。这是一个 MWE:
function getPercent() {
return Math.random() * 100;
}
setInterval(() => {
const per = getPercent();
document.getElementById('foo').style.background =
`linear-gradient(to right, #aebcbf 0%,#aebcbf ${per}%,#0a0e0a ${per}%,#0a0e0a 100%`
}, 1000)
.container {
transition: all 1s ease;
background: linear-gradient(to right, #aebcbf 0%,#6e7774 50%,#0a0e0a 51%,#0a0809 100%);
width: 150px;
height: 10px;
}
<div class="container" id="foo"></div>
最佳答案
希望有用
background: linear-gradient(269deg, #ffffff, #ff0000);
background-size: 400% 400%;
-webkit-animation: AnimationName 23s ease infinite;
-moz-animation: AnimationName 23s ease infinite;
-o-animation: AnimationName 23s ease infinite;
animation: AnimationName 23s ease infinite;
@-webkit-keyframes AnimationName {
0%{background-position:0% 50%}
50%{background-position:100% 50%}
100%{background-position:0% 50%}
}
@-moz-keyframes AnimationName {
0%{background-position:0% 50%}
50%{background-position:100% 50%}
100%{background-position:0% 50%}
}
@-o-keyframes AnimationName {
0%{background-position:0% 50%}
50%{background-position:100% 50%}
100%{background-position:0% 50%}
}
@keyframes AnimationName {
0%{background-position:0% 50%}
50%{background-position:100% 50%}
100%{background-position:0% 50%}
}
有关 CSS 过渡的更多信息,请查看此内容
关于Javascript 使用 CSS3 转换为样式更改设置动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43891175/