簡體   English   中英

如何在元素上重復淡入效果?

[英]How to repeat fade-in effect on element?

更新

添加延遲解決了我的問題:

setTimeout(() => price.classList.add("fade-it"), 100);

原始問題

我對背景顏色有淡入效果,應該由我不時重復。

我正在使用純 CSS:

  <style>
    @-webkit-keyframes yellow-fade {
      from {
        background: #f96;
      }
      to {
        background: #fff;
      }
    }
    @-moz-keyframes yellow-fade {
      from {
        background: #f96;
      }
      to {
        background: #fff;
      }
    }
    @keyframes yellow-fade {
      from {
        background: #f96;
      }
      to {
        background: #fff;
      }
    }
    .fade-it {
      -webkit-animation: yellow-fade 1s ease-in-out 0s;
      -moz-animation: yellow-fade 1s ease-in-out 0s;
      -o-animation: yellow-fade 1s ease-in-out 0s;
      animation: yellow-fade 1s ease-in-out 0s;
    }
  </style>

這個效果已經播放過一次后如何重新開始?

我的代碼在第一次之后不起作用:

    var price = document.getElementById("price");
    if (price.classList.contains("fade-it")) {
      price.classList.remove("fade-it");
    }
    price.classList.add("fade-it");

您可以通過從 DOM 中刪除節點然后將其添加回來來完成此操作。 append function 正是這樣做的,只是 append 元素到它的parentNode 給元素它自己的包裝器作為parentNode這樣它就不會與其他兄弟元素重新排序。

 const price = document.getElementById("price"); const btn = document.getElementById("fade-price"); const fade = function() { if (price.classList.contains("fade-it")) { price.classList.remove("fade-it"); } price.classList.add("fade-it"); } document.addEventListener("DOMContentLoaded", function() { fade() }); btn.addEventListener("click", function() { price.parentElement.append(price) });
 @-webkit-keyframes yellow-fade { from { background: #f96; } to { background: #fff; } } @-moz-keyframes yellow-fade { from { background: #f96; } to { background: #fff; } } @keyframes yellow-fade { from { background: #f96; } to { background: #fff; } }.fade-it { -webkit-animation: yellow-fade 1s ease-in-out 0s; -moz-animation: yellow-fade 1s ease-in-out 0s; -o-animation: yellow-fade 1s ease-in-out 0s; animation: yellow-fade 1s ease-in-out 0s; }
 <div> <h4 id="price">$9.99</h4> </div> <button id="fade-price"> fade </button>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM