js+CSS 图片等比缩小并垂直居中实现代码
更新时间:2008年12月01日 19:57:07 作者:
本例子在在 ff 2.0/ ie6 / ie7 中测试通过。但在 opera 8.5 cn中没有通过。希望大家测试。
复制代码 代码如下:
<!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>
相关文章
JavaScript前端面试扁平数据转tree与tree数据扁平化
这篇文章主要为大家介绍了JavaScript面试中扁平数据转tree以及tree数据扁平化示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-06-06
[Bootstrap-插件使用]Jcrop+fileinput组合实现头像上传功能实例代码
这篇文章主要介绍了[Bootstrap-插件使用]Jcrop+fileinput组合实现头像上传功能实例代码,非常具有实用价值,需要的朋友可以参考下。2016-12-12
WebGL利用FBO完成立方体贴图效果完整实例(附demo源码下载)
这篇文章主要介绍了WebGL利用FBO完成立方体贴图效果的方法,以完整实例形式分析了WebGL实现立方体贴图的具体步骤与相关技巧,并附带了demo源码供读者下载参考,需要的朋友可以参考下2016-01-01


最新评论