2013-08-06 99 views
2

我有一個懸停效果的按鈕(顏色變化)。從js改變css屬性打破css動畫

button { 
    width: 180px; 
    height: 80px; 
    background-color: #A0522D; 
} 

button:hover { 
    background-color: #CD853F; 
} 

然後,從js我想改變背景顏色,例如當選擇的按鈕是正確的。這就是我想出了:

buttons[i].style.backgroundColor = "#A0522D"; 

我也有過渡性質的動畫:

​​

看來,每當我改變背景顏色首次,它完全消除懸停動畫。但是,當我改變字體顏色而不是背景顏色時,情況並非如此。

你知道如何讓懸浮動畫和js動畫改變bgcolor同時工作嗎?或者,我的做法是讓我的按鈕動畫不正確?

回答

2

你可以使用JavaScript更改類。

$('#yourElem').click(function(){ 

    $(this).toggleClass('on') 

}) 

,然後管理與CSS

#yourElem { background-color:red; transition: background-color 500ms ease; } 

#yourElem.on { background-color:blue; } 

所有過渡這將轉換兩個上點擊。

然後,只要你不指定懸停元素與新的轉換,你可以做兩個。

#yourElem { color:black; background-color:red; transition: background-color 500ms ease, color 500ms ease; } 

#yourElem:hover { color:pink; } 

#yourElem.on {color:white; background-color:blue; } 
+0

這個答案確實需要jQuery javascript庫,OP沒有表明他希望/可以使用它。 – cfs

2

這與你的CSS規則的特殊性有關。對元素設置的規則(例如,通過設置style屬性)將比您在CSS文件/樣式塊中聲明的規則具有更高的特異性(除非使用!important)。

更好的方法是使用類設置背景屬性和更改這些元素上,而不是直接設置樣式的:

buttons[i].className = "myClass"; 

StackOverflow answer對如何設置CSS類有很大的說明在JavaScript中。您可以在this article中閱讀關於CSS特異性的更多詳細信息。

+0

謝謝!我是一個新手,並沒有意識到我可以在飛行中改變班級。 – msgmaxim