当前位置: 首页 > 图文教程 > 网络编程 > Javascript > js+CSS 图片等比缩小并垂直居中实现代码

Javascript
编写跨浏览器的javascript代码必备[js多浏览器兼容写法]
JS Array对象入门分析
javascript typeof的用法与typeof运算符介绍[详细]
js CSS操作方法集合
让任务管理器中的CPU跳舞的js代码
ajax无刷新动态调用股票信息(改良版)
js Clip的奇思妙想之文字拼接效果
js Clip奇思妙想之多彩渐变字效果
JS 创建对象(常见的几种方法)
JS中字符问题(二进制/十进制/十六进制及ASCII码之间的转换)
JS提交并解析后台返回的XML的代码
初学Javascript的一些总结
JS 继承实例分析
js form action动态修改方法
仿163填写邮件地址自动显示下拉(无优化)
js判断对象是否是某一类型
解决extjs在firefox中关闭窗口再打开后iframe中js函数访问不到的问题
js 目录列举函数
js颜色选择器代码[firefox不支持]
js wmp操作代码小结(音乐连播功能)

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


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-12   浏览: 97 ::
收藏到网摘: n/a

本例子在在 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.ruanchen.com </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>