我有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的宽度与调整大小时图像的高度相同 . 谢谢您的帮助 .
1 回答
您可以使用以下步骤使用Javascript实现:
1)定义背景图像尺寸(或它们的高度/宽度比) .
2)使用CSS将宽度设置为49%(实际上,可能更好的计算(50% - 边距 - 填充;,但这是一个不同的故事) .
注意:我还更改了inline-block的显示,它比float更优雅:left并且可以防止图像对齐方面的一些问题 .
3)迭代所有的lis .
4)检查图像的实际宽度 . 将宽度x比(高度/宽度)乘以得到所需高度 .
5)设置图像的高度 .
演示作为你的jsfiddle的一个版本:
PD:此代码仅计算一次 . 如果您需要在调整屏幕大小时调整其大小 . 你可以这样做: