2016-09-20 109 views
0

所以我想改變背景圖像使用css過渡, 我有一個問題,這是img沒有反應這種方式 任何人都可以幫助我想出一個辦法會是100%的高度和寬度?改變背景圖像沒有反應

.container{ 
    width:100%; 
    height:600px; 

} 

.container img, .top{ 
    max-width:100%; 
    max-height:100%; 
} 

.top{ 
    width:100%; 
    height:300px; 
    -webkit-transition: background-image 0.5s; 
    display:block; 
} 

.top:before{ 
    content: ""; 
    background-image:url(https://sc02.alicdn.com/kf/HTB1ZRbgIVXXXXXTXXXXq6xXFXXX9/600-x-600-mm-egyptian-tile-keramik.jpg); 
    background-repeat: no-repeat; 
    background-size: contain; 
    -webkit-transition: background 0.5s; 
    width: 100%; 
    height: 100%; 
    display:block; 
} 

.container:hover .top:before { 
    content: ""; 
    background-image: url(http://www.jokopost.com/wp-content/uploads/2015/09/%D7%90%D7%99%D7%A7%D7%A1-commons.wikimedia.org_.png); 
    -webkit-transition: background 1s; 
    width: 100%; 
    height: 100%; 
    display: block; 
} 


<div class="container"> 
<div class="top"> 
</div> 
</div> 

https://jsfiddle.net/7ejtydts/2/

回答

1

使用 「背景尺寸:含有;」會使圖像響應,但不會超出其尺寸。所以你發佈的例子是響應式的,但只有當你減小容器時。

使用「background-size:cover;」將使圖像伸展到容器的大小。這有一個缺點,如果容器的比例不一樣,它會將圖像的邊緣切掉。

看一看我的更新小提琴這裏:

.container{ 
    width:600px; 
    height:600px; 

} 

.container img, .top{ 
    max-width:100%; 
    max-height:100%; 
} 

.top{ 
    width:600px; 
    height:400px; 
    -webkit-transition: background-image 0.5s; 
    display:block; 
} 

.top:before{ 
    content: ""; 
    background-image:url(https://sc02.alicdn.com/kf/HTB1ZRbgIVXXXXXTXXXXq6xXFXXX9/600-x-600-mm-egyptian-tile-keramik.jpg); 
    background-repeat: no-repeat; 
    background-size: cover; 
    background-position: center; 
    -webkit-transition: background 0.5s; 
    width: 100%; 
    height: 100%; 
    display:block; 
} 

.container:hover .top:before { 
    content: ""; 
    background-image: url(http://www.jokopost.com/wp-content/uploads/2015/09/%D7%90%D7%99%D7%A7%D7%A1-commons.wikimedia.org_.png); 
    -webkit-transition: background 1s; 
    width: 100%; 
    height: 100%; 
    display: block; 
} 

https://jsfiddle.net/7ejtydts/3/

+0

好非常感謝,我會嘗試尋找另一種解決方案 – ssabin

+0

你可以看看使用的真實圖像,而不是背景圖片,或者您也可以使用背景圖片,但要確保容器具有固定的寬/高比。或者,你可以使用邊緣周圍有足夠空間的背景圖像,這樣你就可以減少位數,並且看起來沒什麼不同。 –

0

試試這個代碼,它將調整圖像的響應速度。

.top::before { 
    background-image: url("https://sc02.alicdn.com/kf/HTB1ZRbgIVXXXXXTXXXXq6xXFXXX9/600-x-600-mm-egyptian-tile-keramik.jpg"); 
    background-repeat: no-repeat; 
    background-size: contain; 
    content: ""; 
    display: block; 
    height: 100%; 
    left: 0; 
    position: absolute; 
    top: 0; 
    width: 100%; 
} 
.top { 
    display: block; 
    height: 600px; 
    position: relative; 
    width: 100%; 
}