【问题标题】:Bootstrap 3 mouseover image responsiveBootstrap 3 鼠标悬停图像响应
【发布时间】:2014-02-12 08:35:52
【问题描述】:
对于 Bootstrap 3 的响应式图像鼠标悬停是否有任何解决方案?
这是我的代码: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");
}
谢谢!
【问题讨论】:
标签:
jquery
image
css
twitter-bootstrap
twitter-bootstrap-3
【解决方案1】:
它将需要更多的 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(因此图像的宽度是高度的两倍),那么 .wrapper-with-intrinsic-ratio 上的 padding-bottom 将是 50%。用 (height ÷ width) × 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。
【讨论】:
-
没问题。两件事:这是some documentation on background-size。其次,纵横比可能很棘手:如果比例是 2:1(因此图像的宽是高的两倍),那么 .wrapper-with-intrinsic-ratio 上的 padding-bottom 将是 50%。用(高 ÷ 宽)×100 计算出来。所以对于 350×150 像素的图像,它是 padding-bottom: 42.857%;,对于 150x350 像素,它是 233.333%。我会将其编辑为答案。
【解决方案2】:
或者你可以只使用一个简单的 onmouseover html 标签并从引导程序中给它一个 img-responsive 类。
.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/