簡體   English   中英

jQuery單擊時對元素應用過渡

[英]jQuery apply transition on element on click

每次單擊按鈕時,我都嘗試應用淡入淡出過渡。

實現此目的的最佳實踐是什么?

因此,想象一下.apply()而不是.addClass()然后添加后的.removeClass(),它將僅應用一次該類,從而不會“保留”該類。

現在,我有了.toggleClass ,它僅每隔.toggleClass單擊就應用過渡(基本上像:addClass,removeClass,addClass等)。 我可以考慮通過另一種方法來查看它是否已經具有該類,如果沒有,則將其刪除並再次添加,但這似乎違反直覺,使我認為必須采用一種更簡單,更簡潔的方法去做這個。

 $("#btn").click(function() { $("#cat").toggleClass("fade"); }) 
 @import url('https://fonts.googleapis.com/css?family=Yatra+One'); body, html { height: 100%; width: 100%; margin: 0; } body { display: flex; flex-direction: column; justify-content: center; align-items: center; background-color: #eee; } .generator { height: 400px; width: 400px; display: flex; flex-direction: column; justify-content: space-between; align-items: center; } #cat { height: 300px; width: 400px; border-radius: 5px; transform: scale(1); opacity: 1; } .fade { animation: fade .5s linear forwards; } @keyframes fade { 0% { transform: scale(1); opacity: 1; } 50% { transform: scale(0); opacity: 0; } 100% { transform: scale(1); opacity: 1; } } #btn { height: 90px; width: 400px; outline: none; border: none; border-radius: 5px; background-color: #4682B4; color: white; font-size: 1.75em; font-family: Yatra One; transition: background-color 0.1s ease-in-out; } #btn:hover { cursor: pointer; background-color: #508EC3; } #btn:active { background-color: #4293D8; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="container"> <div class="generator"> <img id="cat" src="https://i.imgur.com/RVQZ9UM.png" alt="cat" /> <button id="btn">New cat</button> </div> </div> 

您可以通過聽動畫事件來刪除動畫末尾的fade類:

$("#cat").bind('oanimationend animationend webkitAnimationEnd', function() { 
   $(this).removeClass("fade");
});

在這種情況下,您可以使用addClass而不是toggleClass

在此處使用toogleClass()可能不是最佳解決方案。 發生的是:

  1. 在啟動時<img>沒有.fade
  2. 當您單擊按鈕時,將添加類,從而啟動關鍵幀動畫
  3. 但是當您再次單擊時,它將刪除該類
  4. 因此,您必須再單擊一次以重新啟動動畫

但是目前,我還沒有更好的方法。 而且,Nandita的答案實際上具有相同的行為,但代碼更多。

阿里的那個實際上是最好的一個:

$("#btn").click(function() {
      $("#cat").addClass("fade");
})

$("#cat").bind('oanimationend animationend webkitAnimationEnd', function() { 
   $(this).removeClass("fade");
});

完成動畫后,偵聽動畫事件以刪除.fade類。

暫無
暫無

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

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