2016-01-14 206 views
3

我需要自動改變元素的顏色以無限地運行,下面的代碼實現了我想要的效果,但只有當鼠標通過元素(div)時纔會發生。我怎麼做,所以它總是改變顏色?懸停時不停地變換顏色

感謝和問候。

.box{ 
background-color: #900; 
height: 50px; 
width: 100px; 
padding: 1em; 
color: #fff; 
font-weight: bold; 
transition:background-color 3s linear; 
-webkit-transition:background-color 3s linear; 
-o-transition: background-color 3s linear; 
-moz-transition: background-color 3s linear; 
-ms-transition: background-color 3s linear; 

} 

.box:hover{ 
background-color: #090; 


} 
+0

當鼠標進入你想要過渡到infintely運行顏色之間改變,而不停止元素的DIV?請澄清您的要求.... – repzero

回答

3

你可以用CSS keyframes來做到這一點。

@keyframes changeColor { 
 
    0% { 
 
    background-color: #900; 
 
    } 
 
    50% { 
 
    background-color: #090; 
 
    } 
 
    100% { 
 
    background-color: #900; 
 
    } 
 
} 
 
.box { 
 
    animation-name: changeColor; 
 
    animation-iteration-count: infinite; 
 
    animation-duration: 3s; 
 
    background-color: #900; 
 
    height: 50px; 
 
    width: 100px; 
 
    padding: 1em; 
 
    color: #fff; 
 
    font-weight: bold; 
 
}
<div class="box"></div>

+0

非常感謝! –

+0

當然,這是解決方案嗎? –

1

可以實現通過使用CSS動畫(關鍵幀)這個效果。閱讀here

.box { 
 
    background-color: #900; 
 
    height: 50px; 
 
    width: 100px; 
 
    padding: 1em; 
 
    color: #fff; 
 
    font-weight: bold; 
 
    transition: background-color 3s linear; 
 
    -webkit-transition: background-color 3s linear; 
 
    -o-transition: background-color 3s linear; 
 
    -moz-transition: background-color 3s linear; 
 
    -ms-transition: background-color 3s linear; 
 
} 
 
@keyframes hoverme { 
 
    0% { 
 
    background-color: #900; 
 
    } 
 
    25% { 
 
    background-color: red; 
 
    } 
 
    50% { 
 
    background-color: green; 
 
    } 
 
    25% { 
 
    background-color: red; 
 
    } 
 
    100% { 
 
    background-color: #900; 
 
    } 
 
} 
 
.box:hover { 
 
    animation: hoverme 3s infinite; 
 
}
<div class="box"> 
 
    Hover me :) 
 
</div>