【问题标题】:Keep ratio height of div with background image in responsive保持div的比例高度与背景图像响应
【发布时间】:2017-04-16 03:36:50
【问题描述】:

我有带有 li 的 html 包含背景图像,但我想保持 li 的大小以相同的图像大小比例响应:

<ul>
    <li><a href="#">hello</a></li>
    <li><a href="#">hello1</a></li>
    <li><a href="#">hello2</a></li>
</ul>
<style>
ul li {width:49%; float:left; height:auto}
ul li:nth-child(1) {background:url(url1) no-repeat left top; background-size:100% auto;}
ul li:nth-child(2) {background:url(url2) no-repeat left top; background-size:100% auto;} 
ul li:nth-child(3) {background:url(url3) no-repeat left top; background-size:100% auto;} 
</style>

正如您在jsfiddle 中看到的,它包含全宽但高度被裁剪。 我希望 li 的宽度与调整大小时图像的高度具有相同的比例。感谢您的帮助。

【问题讨论】:

  • 任何人请帮助我。谢谢

标签: jquery html css


【解决方案1】:

您可以通过以下步骤使用 Javascript 实现:

1) 定义背景图片尺寸(或它们的高/宽比)。

var image_dimensions = [
  [512, 320],
  [512, 288],
  [512, 358],
];

2) 使用 CSS 将宽度设置为 49%(实际上,计算可能更好(50% - margin - padding;,但那是另一回事)。

ul li {
  display: inline-block;
  width: calc(50% - 2px);
}

注意:我还更改了 inline-block 的显示,它比 float:left 更优雅,并且可以防止图像对齐方面的一些问题。

3) 迭代所有的 lis。

var images = document.querySelectorAll('ul#image_list li');

for (var i = 0; i < image_dimensions.length && i < images.length; i++){

4) 检查图像的实际宽度。乘以得到所需高度的宽度 x 比率(高度/宽度)。

var ratio = image_dimensions[i][1] / image_dimensions[i][0];
var height = images[i].offsetWidth * ratio;

5) 设置图片的高度。

images[i].style.height = height + 'px';

演示作为你的 jsfiddle 的一个版本:

var image_dimensions = [
	[512, 320],
  [512, 288],
  [512, 358],
];

var images = document.querySelectorAll('ul#image_list li');

for (var i = 0; i < image_dimensions.length && i < images.length; i++){
  var ratio = image_dimensions[i][1] / image_dimensions[i][0];
  var height = images[i].offsetWidth * ratio;
  images[i].style.height = height + 'px';
}
ul li {
  display: inline-block;
  width: calc(50% - 2px);
}

ul li:nth-child(1) {background:url("http://1.bp.blogspot.com/-XlNXQh-wWx0/VEvOnrhNi-I/AAAAAAAAHfY/EMUT8ZWkjZ0//autumn-sad-heart-free-desktop-wallpaper-1920x1200.jpg") no-repeat left top;background-size: 100% auto;}
ul li:nth-child(2) {background:url("http://4.bp.blogspot.com/-Ng8xrfA_UuY/VEvMCERa3LI/AAAAAAAAHdw/R3V7Tv5BgXg//fg.jpg") no-repeat left top; background-size:100% auto;} 
ul li:nth-child(3) {background:url("http://3.bp.blogspot.com/-VcuSwUBvb_Q/VEvNn6LSBBI/AAAAAAAAHfA/llfaD-qwBlU//vintage-letter-free-desktop-wallpaper-5672x3970.jpg") no-repeat left top; background-size:100% auto;} 
<ul id="image_list">
    <li><a href="#">hello</a></li>
    <li><a href="#">hello1</a></li>
    <li><a href="#">hello2</a></li>
</ul>

PD:此代码仅计算一次。如果您需要在更改屏幕大小时调整其大小。你可以这样做:

window.onresize = function(){
  // wrap all the previous code here too.
  // Or better, move it to a function and call it both on window.onload and window.onresize
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多