它需要更多的HTML代碼,但您可以使用與http://alistapart.com/article/creating-intrinsic-ratios-for-video/相同的基本技巧。您需要在某處設置寬度(因爲背景圖像沒有內在尺寸),但可能來自父元素。基本上:
<div class="wrapper-with-intrinsic-ratio"><div class="element-to-stretch"></div></div>
.wrapper-with-intrinsic-ratio {
position: relative;
padding-bottom: 20%; /* Adjust this to suit the aspect ratio of the image */
height: 0;
width: 100%;
}
.element-to-stretch {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-image: url("http://placehold.it/350x150/000/fff");
background-size: cover;
}
.element-to-stretch:hover {
background-image: url("http://placehold.it/350x150/ccc/fff");
}
這是的some documentation on background-size。其次,高寬比可能會非常棘手:如果比例爲2:1(因此圖像的寬度是其高度的兩倍),則上的padding-bottom
將爲50%
。用(高度÷寬度)×100來解決這個問題。例如,你的350×150px圖像應該是padding-bottom: 42.857%;
和150x350px it'd be 233.333%
。
或者,你可以用兩個img元素來完成。笨重,但...
<div>
<img src="normal.jpg" alt="" class="normal"><img src="hover.jpg" alt="" class="hover">
</div>
div img { max-width: 100%; height: auto; }
div img.normal,
div:hover img.hover { display: block; }
div img.hover,
div:hover img.normal { display: none; }
或者您可以使用javascript。
你能解釋一下嗎?我不明白。 – pbenard
我想有這樣的響應鼠標懸停圖像http://jsfiddle.net/4gac7/1/在手機上,我可以觸摸圖像,我會看到鼠標在圖像上。問題 - 沒有響應,因爲div需要寬度和高度。 – l00per