[英]Animating a div back and forth
我不是專家。 我正在尋找一點幫助。
我試圖使用toggleClass來回移動div;
$('div').on('click', function() {
$(this).toggleClass('active');
});
和關鍵幀;
.active {
animation-name: moveme;
animation-duration: 1s;
animation-timing-function: linear;
animation-fill-mode: forwards;
}
@keyframes moveme {
0% {transform: translate(0,0)}
50% {transform: translate(-200px, 0px)}
100% {transform: translate(-200px,-50px);}
}
現在,當div返回其先前的位置時,它不會生成動畫。 我希望div使用相同的動畫制作動畫,但是向后。 我怎樣才能做到這一點?
在這里你可以看到我正在努力實現的目標jsfiddle.net/jmrMW/43/我為了這個例子而做了一個簡單的動畫,但是將來它會變得更復雜。
提前謝謝^^
這是你的JSFiddle的一個分支。 幾乎只是重復你已經擁有的關鍵幀,但反過來應用它:)
$('div').on('click', function() { if ( $(this).hasClass("go-up") ) { $(this).removeClass("go-up").addClass("go-down"); } else { $(this).addClass("go-up").removeClass("go-down"); } });
div{ background:#aaa; width: 200px; margin: 20vh auto; height: 200px; } .go-up { animation-name: moveup; animation-duration: 1s; animation-timing-function: linear; animation-delay: 0s; animation-fill-mode: forwards; } .go-down { animation-name: movedown; animation-duration: 1s; animation-timing-function: linear; animation-delay: 0s; animation-fill-mode: forwards; } @keyframes moveup { 0% {transform: translate(0,0)} 50% {transform: translate(-100px, 0px)} 100% {transform: translate(-100px,-50px);} } @keyframes movedown { 0% {transform: translate(-100px,-50px);} 50% {transform: translate(-100px, 0px)} 100% {transform: translate(0,0)} }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div></div>
Javascript立即添加和刪除類。 而你的CSS只將動畫綁定到.active
類,所以當你第二次點擊時 - 你松開了你的課程 - 你就會失去輕微的動畫。
現在,您可以復制人們在我之前提到的所有內容,但請繼續! 程序員從不復制,他們使用。 發現CSS3動畫的所有功能不是一個好主意嗎?
所以,我想建議另一種方法:設置animation-direction: alternate
和animation-play-state: paused
。 然后定義用於移動的CSS類,無論哪種方式:
.moving {
animation-play-state: running;
}
然后,在單擊后將其應用於給定元素僅1秒:
var $moveable = $( '.moveable' ).eq( 0 );
$moveable.click(function() {
$moveable.addClass( 'moving' );
setTimeout(function() {
$moveable.removeClass( 'moving' );
}, 1000);
});
更新
這個解決方案有一個主要的缺點 - 在JS和CSS中使用計時器顯然是不匹配的。 動畫現在是無限的,所以每次動畫都比應該的更進一步。 但我們可以增加animation-iteration-count
來禁用動畫進入下一個循環。 希望這仍然很有趣!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.