js+CSS 图片等比缩小并垂直居中实现代码

2019-12-25,,

复制代码 代码如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>图片自动等比例缩小且垂直居中-www.jb51.net </title>
<!--[if lte IE 6]>
<script type="text/javascript" language="javascript">
function imgFix() {
//定义要限制的图片宽高,这个宽高要同style里面定义的相同,小于限定高宽的图片不操作
var widthRestriction = 200;
var heightRestriction = 200;
var allElements = document.getElementsByTagName('*')
for (var i = 0; i < allElements.length; i++)
{
if (allElements[i].className.indexOf('imgBox') >= 0)
{
var imgElements = allElements[i].getElementsByTagName('img');
for (var j=0; j < imgElements.length; j++)
{
if ( imgElements[j].width > widthRestriction || imgElements[j].height > heightRestriction )
{
if ( imgElements[j].width > imgElements[j].height)
{
imgElements[j].height = imgElements[j].height*(widthRestriction/imgElements[j].width);
imgElements[j].width = widthRestriction;
} else
{
imgElements[j].width = imgElements[j].width*(heightRestriction/imgElements[j].height);
imgElements[j].height = heightRestriction;
}
}
if ( imgElements[j].height < heightRestriction )
{
imgElements[j].style.paddingTop = ( heightRestriction -imgElements[j].height ) /2 + "px";
}
} /*for j*/
}
}/*for i*/
}
window.onload = imgFix;
</script>
<![endif]-->
<style type="text/css">
<!--
* {
margin:0;
padding:0;
}
.imgBox li {
list-style:none;
width:200px; /* 宽度 */
height:200px; /* 高度 */
background:#ccc;
border:1px solid #666;
text-align:center;
margin:5px;
line-height:200px;
}
.imgBox img {
max-width:200px; /* 宽度 */
max-height:200px; /* 高度 */
vertical-align:middle;
}
-->
</style>
</head>
<body>
<ul class="imgBox">
<li><img src="......" alt="img" /></li>
<li><img src="......" alt="img" /></li>
<li><img src="......" alt="img" /></li>
<li><img src="......" alt="img" /></li>
</ul>
</body>
</html>

您可能感兴趣的文章:

  • iOS - UIButton(UIEdgeInsets)/设置button上的文字和图片上下垂直居中对齐
  • CSS图片响应式 垂直水平居中
  • javascript图片自动缩放和垂直居中处理函数
  • 用css实现图片垂直居中的使用技巧
  • 未知大小图片在已知容器中的垂直和水平居中问题
  • 文字或图片元素在DIV中垂直居中
  • JS实现图片垂直居中显示小结

《js+CSS 图片等比缩小并垂直居中实现代码.doc》

下载本文的Word格式文档,以方便收藏与打印。