2017-06-23 43 views
4

我有一個簡單的藍色方塊,我想控制2個按鈕,「向左移動」「向右移動」CSS - 共享@Keyframes規則集與動畫方向和動畫 - 填充模式?

  • 左移:應該從右側移動藍色正方形到左邊,褪色0.5的不透明度爲1,並保持該動畫的最後一幀。

  • 向右移動:應將藍色方塊從左向右移動,將不透明度從1淡入0.5,並保留動畫的最後一幀。

我想分享一個@keyframes move規則集,但我很困惑與如何animation-directionanimation-fill-mode應該共同努力。

動畫第一次被觸發是正確的,無論動畫是向左還是向右移動,但在此之後它不再像它應該那樣動畫。

const square = document.getElementById("square"); 
 

 
const leftButton = document.getElementById("left"); 
 
leftButton.addEventListener("click",() => { 
 
    square.classList.remove("moveRight"); 
 
    square.classList.add("moveLeft"); 
 
}); 
 

 
const rightButton = document.getElementById("right") 
 
rightButton.addEventListener("click",() => { 
 
    square.classList.remove("moveLeft"); 
 
    square.classList.add("moveRight"); 
 
})
#square { 
 
    width: 200px; 
 
    height: 200px; 
 
    background-color: blue; 
 
    margin-top: 20px; 
 
    position: relative; 
 
} 
 
    
 
.moveLeft { 
 
    animation: move 1s linear normal forwards; 
 
} 
 
    
 
.moveRight { 
 
    animation: move 1s linear reverse forwards; 
 
} 
 
    
 
@keyframes move { 
 
    from {left: 100px; opacity: 0.5;} 
 
    to {left: 0; opacity 1;} 
 
}
<input type="button" id="left" value="MOVE LEFT"> 
 
<input type="button" id="right" value="MOVE RIGHT"> 
 

 
<div id="square"></div>

回答

1

你可以做到這一點,而無需使用transition的動畫。

const square = document.getElementById("square"); 
 

 
const leftButton = document.getElementById("left"); 
 
leftButton.addEventListener("click",() => { 
 
    square.classList.remove("moveRight"); 
 
    square.classList.add("moveLeft"); 
 
}); 
 

 
const rightButton = document.getElementById("right") 
 
rightButton.addEventListener("click",() => { 
 
    square.classList.remove("moveLeft"); 
 
    square.classList.add("moveRight"); 
 
})
#square { 
 
    width: 200px; 
 
    height: 200px; 
 
    background-color: blue; 
 
    margin-top: 20px; 
 
    position: relative; 
 
    transition: transform 1s, opacity 1s; 
 
} 
 
    
 
.moveLeft { 
 
    transform: translateX(0); 
 
    opacity: 1; 
 
} 
 
    
 
.moveRight { 
 
    transform: translateX(100px); 
 
    opacity: .5; 
 
}
<input type="button" id="left" value="MOVE LEFT"> 
 
<input type="button" id="right" value="MOVE RIGHT"> 
 

 
<div id="square"></div>

+0

謝謝您的回答。但是,如果我有更復雜的動畫,需要使用'animation'而不是'transition',我想知道如何共享'@keyframes'規則集。例如,如果藍色方塊的初始不透明度爲0,則按下「向左移動」仍應該使用動畫的「到/從」或「0%50%100%」來爲廣場製作動畫。 – TheDarkIn1978

+0

@ TheDark1978歡迎您。我不確定動畫爲什麼不起作用。我可以繼續看着它。你是否希望我刪除這個答案,因爲它「沒有用處」,或者將它留作替代方法,以供將來發現此問題的任何人使用? –

+0

不要刪除答案,我確信其他人可能會覺得它有用。但是,如果您找到解決方案,請編輯您的答案。 – TheDarkIn1978