Javascript 使用 CSS3 转换为样式更改设置动画

标签 javascript html css

我有一个具有背景渐变的 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/

相关文章:

javascript - 如何将嵌套对象拆分为对象数组 - 避免 for 循环

javascript - 从服务器拉取消息并在客户端渲染

html - 让 span 不占用或使用空间,以便在 span 消失时关闭元素不移动

html - select、input 和 label 元素有 height 属性吗?

html - 占位符无法在所有浏览器中正常工作

css - Z-index 绝对定位背景图

javascript - 函数组合的意外行为

javascript - ServiceWorker 'fetch' 事件未针对图标触发

html - 将每个 <td> 正方形设为任意表格宽度

html - 在悬停之前或之后颜色不起作用