简体   繁体   English

使用CSS在click事件上分别对每个transform属性进行动画处理

[英]Animate each transform property separately on click event using CSS

I want that whenever I click on the div , it first translate , then rotate and, finally scale . 我希望每当我单击div ,它首先translate ,然后rotate ,最后scale Further, I want to reverse it back in the same way when I click again 此外,当我再次单击时,我想以相同的方式将其reverse it back

I have the following code: 我有以下代码:

 $(() => { $('div').on('click', () => { $('div').toggleClass('clicked'); }); }); 
 div.normal { height: 20px; width: 100px; background: black; transition: 2s all; } div.clicked { transform: translate(100px, 100px) rotate(45deg) scale(2); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='normal'></div> 

As you can see, all the transformations are occurring at the same time. 如您所见,所有转换都是同时发生的。 But, I want them to occur separately. 但是,我希望它们分开出现。 How do I achieve this? 我该如何实现?

Thanks in advance! 提前致谢!

Decompose your animation using keyframes. 使用关键帧分解动画。 Here is a minimally edited version of your code: 这是代码的最低编辑版本:

 var $el = $('#to-animate') var firstClick = true $el.click(() => { $el.toggleClass('clicked') if (!firstClick) { $el.toggleClass('unclicked') } firstClick = false }) 
 div.normal { height: 20px; width: 100px; background: black; } div.clicked { animation: transforms 2s forwards; } div.unclicked { animation: transforms-2 2s reverse; } @keyframes transforms { 33% { transform: translate(100px, 100px); } 66% { transform: translate(100px, 100px) rotate(45deg); } 100% { transform: translate(100px, 100px) rotate(45deg) scale(2); } } @keyframes transforms-2 { 33% { transform: translate(100px, 100px); } 66% { transform: translate(100px, 100px) rotate(45deg); } 100% { transform: translate(100px, 100px) rotate(45deg) scale(2); } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="to-animate" class='normal'></div> 

Edit updated to include ability to reverse the animation (making the code edit less minimal) 编辑已更新,包括反转动画的能力(使代码编辑的最小限度减少)

An idea is to rely on other properties to achieve the same effect and be able to apply different transition 一个想法是依靠其他属性来达到相同的效果并能够应用不同的过渡

 $(() => { $('div').on('click', () => { $('div').toggleClass('clicked'); }); }); 
 div.normal { height: calc(20px * var(--s,1)); width: calc(100px * var(--s,1)); background: black; position:relative; top:0; left:0; transition: 2s top 4s,2s left 4s,2s width 2s,2s height 2s,2s transform; } div.clicked { top:100px; left:100px; --s:2; transform:rotate(45deg); transition: 2s top,2s left,2s width 2s,2s height 2s,2s transform 4s; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='normal'></div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM