2014-01-22 69 views
1

Bootstrap 3有沒有解決方案來響應圖像mouseover?Bootstrap 3 mouseover image responsive

這裏是我的代碼:http://jsfiddle.net/4gac7/

.image{ 
background-image:url("http://placehold.it/350x150/000/fff"); 
width:350px; /* responsive possible ?? */ 
height:150px; 

} 
.image:hover{ 
background-image:url("http://placehold.it/350x150/ccc/fff"); 
} 

謝謝!

+0

你能解釋一下嗎?我不明白。 – pbenard

+0

我想有這樣的響應鼠標懸停圖像http://jsfiddle.net/4gac7/1/在手機上,我可以觸摸圖像,我會看到鼠標在圖像上。問題 - 沒有響應,因爲div需要寬度和高度。 – l00per

回答

3

它需要更多的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。

+1

哦,這看起來非常好。謝謝! http://jsfiddle.net/4gac7/2/ – l00per

+0

沒問題。有兩件事:這裏是[關於背景大小的一些文檔](https://developer.mozilla.org/en-US/docs/Web/CSS/background-size)。其次,寬高比可能比較棘手:如果比例是2:1(因此圖像寬度是高度的兩倍),那麼'.wrapper-with-intrinsic-ratio'上的'padding-bottom'將是' 50%'。用(高度÷寬度)×100來解決這個問題。因此,對於一個350×150像素的圖像,它應該是「padding-bottom:42.857%;'而對於150x350像素則是'233.333%'。我會將其編輯爲答案。 –

1

或者你可以只使用一個簡單的onmouseover html標記&從bootstrap給它一個img響應類。

.img-responsive, 
 
.thumbnail > img, 
 
.thumbnail a > img, 
 
.carousel-inner > .item > img, 
 
.carousel-inner > .item > a > img { 
 
    display: block; 
 
    max-width: 100%; 
 
    height: auto; 
 
}
<div class="col-lg-6"> 
 
<img src="http://placehold.it/350x150/000/fff" onmouseover="this.src='http://placehold.it/350x150/ccc/fff'" onmouseout="this.src='http://placehold.it/350x150/000/fff'" class="img-responsive"> 
 
</div>

http://jsfiddle.net/McKmillions/7t63cja2/

+0

很簡單..謝謝 –