【问题标题】:How to change colour of a <label> in html dynamically with time如何随时间动态更改 html 中 <label> 的颜色
【发布时间】:2017-05-27 23:39:31
【问题描述】:

如何编写代码以动态更改 html 中元素的颜色。 例如:如果 Hello 是标签,从前 2 秒开始,它应该将颜色变为黄色,然后变为绿色,依此类推,并带有过渡效果。谢谢

【问题讨论】:

标签: javascript css html


【解决方案1】:

animation 可以做到这一点:

label {
  animation:colorchg 2s infinite;
  color:green
}
@keyframes colorchg {
  50% {
    color:red;
  }
}
&lt;label&gt;color&lt;/label&gt;

【讨论】:

    【解决方案2】:

    如何使用 CSS3 动画。我从 W3Schools 中获得了这个概念。看看吧

    您可以通过除以百分比来添加更多背景颜色。

    label {
    
        background-color: red;
    
        -webkit-animation-name: example; /* Safari 4.0 - 8.0 */
        -webkit-animation-duration: 1s; /* Safari 4.0 - 8.0 */
        -webkit-animation-delay: 1s; /* Safari 4.0 - 8.0 */
        animation-name: example;
        animation-duration: 1s;
        animation-delay: 1s;
        animation-iteration-count: infinite;
    }
    
    /* Safari 4.0 - 8.0 */
    @-webkit-keyframes example {
        0%   {background-color:red; }
        25%  {background-color:yellow; }
        50%  {background-color:blue; }
        75%  {background-color:green; }
        100% {background-color:red; }
    }
    
    /* Standard syntax */
    @keyframes example {
        0%   {background-color:red; ;}
        25%  {background-color:yellow; }
        50%  {background-color:blue;}
        75%  {background-color:green; }
        100% {background-color:red; }
    }
    &lt;label&gt;Mylabel&lt;/label&gt;

    【讨论】:

      【解决方案3】:

      我建议在 CSS 中执行此操作,但如果您想要 JS 解决方案,您可以使用 setInterval() 定义间隔并切换指定颜色的类或只是更改 element.style.color 或其他任何内容,并使用 CSS 过渡来过渡颜色变化。

      var interval = setInterval(function () {
        label.classList.toggle('color');
      },2000)
      label {
        transition: 2s;
        color: green;
      }
      .color {
        color: red;
      }
      &lt;label id="label"&gt;text&lt;/label&gt;

      【讨论】:

        猜你喜欢
        • 2013-07-11
        • 2011-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-17
        • 2012-03-25
        • 1970-01-01
        • 2012-11-08
        相关资源
        最近更新 更多