当前位置: 首页 > 图文教程 > 网络编程 > Javascript > javascript图片自动缩放和垂直居中处理函数

Javascript
实现表格中行点击时的渐扩效果!
多图展示滑动过渡效果
弹出自适应图片大小的窗口弹出窗口根据图片大小,自动判断高和宽。
拖动Html元素集合 Drag and Drop any item
脚本吧 - 幻宇工作室用到js,超强推荐base.js
使用透明叠加法美化文件上传界面
JavaScript高级程序设计
对象的类型:本地对象(1)
如何实现表格中行点击时的渐扩效果!
使用button标签,实现三态图片按钮
根据分辩率调用不同的CSS.
Web版彷 Visual Studio 2003 颜色选择器
JS中简单的实现像C#中using功能(有源码下载)
js之WEB开发调试利器:Firebug 下载
jQuery中文入门指南,翻译加实例,jQuery的起点教程
jQuery 1.0.4 - New Wave Javascript(js源文件)
强悍无比的WEB开发好助手FireBug(Firefox Plugin)
换肤测试程序js脚本
xWin之JS版(2-26更新)
共享自己写一个框架DreamScript

Javascript 中的 javascript图片自动缩放和垂直居中处理函数


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

非常不错的应用代码,方便我们处理一些图片效果
复制代码 代码如下:

<html>
<head>
<title>Untitled</title>
<style type="text/css">
.testCss{width:200px;height:300px;border:1px red solid;text-align:center;display:block;}
.testCss1{width:300px;height:300px;border:1px red solid;text-align:center;display:block;}
.testCss2{width:400px;height:300px;border:1px red solid;text-align:center;display:block;}
</style>
<script type="text/javascript">
function autoSizeImg(Contents,offsetWidth,offsetHeight,vlmiddle){
var o=Contents.getElementsByTagName("IMG");
var cwidth= window.getComputedStyle?window.getComputedStyle(Contents,null).width:Contents.currentStyle["width"];
var cheight=window.getComputedStyle?window.getComputedStyle(Contents,null).height:Contents.currentStyle["height"];
var ncwidth=parseInt(cwidth);
var ncheight=parseInt(cheight);
for(var i=0;i<o.length;i++){
var img=o[i];
var iw=img.width;
var ih=img.height;
if(img.width>ncwidth){
var nw=ncwidth-offsetWidth;
img.width=nw
img.height=(nw*ih)/iw;
}else if(img.width<ncwidth&&img.height>ncheight){
var nh=ncheight-offsetHeight;
img.height=nh;
img.width=(nh*iw)/ih;
}
if(img.height>ncheight&&img.width<ncwidth){
var hh=ncheight-offsetHeight;
img.height=nh;
img.width=(nh*iw)/ih;
}
if(vlmiddle)img.style.marginTop=((ncheight-img.height)/2)+"px";
}
}
</script>
</head>
<body>
<div class="testCss">
<img src="/upload/tech/20091012/20091012093235_c52f1bd66cc19d05628bd8bf27af3ad6.jpg" onload="autoSizeImg(this.parentNode,5,5,true)"/>
</div>
<div class="testCss1">
<img src="/upload/tech/20091012/20091012093241_470e7a4f017a5476afb7eeb3f8b96f9b.jpg" onload="autoSizeImg(this.parentNode,5,5,true)"/>
</div>
<div> </div>
<div class="testCss2">
<img src="/upload/tech/20091012/20091012093243_3621f1454cacf995530ea53652ddf8fb.gif" onload="autoSizeImg(this.parentNode,5,5,true)"/>
</div>
</body>
</html>

注释:
1、后面的testCss1和testCss2两个样式跟testCss是一样的。只是设置了大小。
2、红色部分的height和width必须定义,是设置存放img外面的父层容器的高和宽。
3、text-algin:为图片水平居中
4、display:block,必须设置。否则FF下启用自动缩放不起作用。
使用方法:
1、是需要在img的父层定义样式,包含上述注释里面提到的东西;
2、是img加上

onload="autoSizeImg(this.parentNode,5,5,true)"
参数说明:
参数Contents一般采用this.parentNode,即使img的父容易
参数offsetWidth,offsetHeight分别是宽和高度居中的修正值。
参数vlmiddle设置为true则是垂直居中
点击运行可以看到效果:
[Ctrl+A 全选 提示:你可先修改部分代码,再按运行]