2017-07-31 187 views
0

我正試圖在背景圖像的面板上進行基本的平滑過渡。我希望它在徘徊時褪色爲背景色。我嘗試過使用各種各樣的非轉換工作。我已經試過(我本以爲這工作):背景圖像和背景顏色之間的CSS過渡

transition:background-image 0.2s ease-in-out; 

.panel { 
 
    width:200px; 
 
    height:200px; 
 
    background:#000 url("https://cdn.pixabay.com/photo/2016/03/28/12/35/cat-1285634_1280.png") no-repeat center center/cover; 
 
    transition:background-image 0.2s ease-in-out; 
 
} 
 
.panel:hover { 
 
    background:#000; 
 
    transition:background-image 0.2s ease-in-out; 
 
}
<div class="panel"></div>

回答

1

您可以使用此代碼:

演示是在這裏:https://output.jsbin.com/yadiwoviwe

.panel { 
    position: relative; 
    background: rgba(0,0,0,0) url(https://cdn.pixabay.com/photo/2016/03/28/12/35/cat-1285634_1280.png) no-repeat center center/cover; 
    width:200px; 
    height:200px; 
    transition: background-color 0.2s ease-in-out; 
} 
.panel:hover { 
    background-color: rgba(0,0,0,.5); 
} 
.panel:before { 
    position: absolute; 
    top: 0; right: 0; bottom: 0; left: 0; 
    background-color: inherit; 
    content: ' '; 
} 
+0

這會工作,但如果我想添加面板格內的任何文字內容也將淡出說出來了。 – alexgomy

+0

我可以解決文本問題。謝謝 – alexgomy

1

不幸的是,你不能在這個w中這樣做ay

原因是,您正在嘗試爲background-image屬性設置動畫效果 - 這是一種不具動畫效果的屬性。

相反,你可以使用使用僞元素涼爽的小動作來創建背景圖像,而不是:

.panel { 
 
    width: 200px; 
 
    height: 200px; 
 
    position: relative; 
 
    background: pink; 
 
} 
 

 
.panel::after { 
 
    content: ""; 
 
    position: absolute; 
 
    pointer-events: none; 
 
    background: url(https://unsplash.it/200) center center no-repeat; 
 
    top: 0; 
 
    right: 0; 
 
    bottom: 0; 
 
    left: 0; 
 
    z-index: 1; 
 
    will-change: opacity; 
 
    transition: opacity .1s ease-out; 
 
} 
 

 
.panel:hover::after { 
 
    opacity: 0.5; 
 
}
<div class="panel"></div>

上CSSTricks

0

背景 - 靈感來自this cool little article圖像不具有動畫效果,因此無法在backgronund-image屬性上添加轉場。 您可以使用其他變通方法解決這個像@CGK答案

background: rgba(0,0,0,0) url(https://cdn.pixabay.com/photo/2016/03/28/12/35/cat-1285634_1280.png) no-repeat center center/cover; 
0

或者,您可以處理圖像的不透明度。

.panel { 
 
    width: 200px; 
 
    height: 200px; 
 
    background: #000; 
 
    position: relative; 
 
    color: white; 
 
    text-align: center; 
 
} 
 

 
.panel:after { 
 
    content: ""; 
 
    background-image: url('https://cdn.pixabay.com/photo/2016/03/28/12/35/cat-1285634_1280.png'); 
 
    background-size: 200px 200px; 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
    width: 200px; 
 
    height: 200px; 
 
    opacity: 1; 
 
    transition: opacity 0.2s ease-in-out; 
 
} 
 

 
.panel:hover:after { 
 
    opacity: 0; 
 
}
<div class="panel"><h1>Text</h1></div>