您的位置:首页 > Web前端 > HTML

html页面中图片自适应容器大小且上下左右居中插件

2012-11-15 15:24 561 查看
概述

做了一个通用的图片自适应插件,方便大家使用,下面直接上代码。

插件源码
// jQuery.imgAutoSize.js
// Wangbaifeng - http://donglisoft.com/ - MIT Licensed
(function ($) {

$.fn.imgAutoSize = function () {
this.each(function () {
var pwidth = $(this).width();
var pheight = $(this).height();
var _img = $(this).find("img");
var iwidth = _img.width();
var iheight = _img.height();

//alert(pwidth + "-" + pheight + "-" + iwidth + "-" + iheight)

if (pwidth <= iwidth || pheight <= iheight) {
if (iwidth / pwidth > iheight / pheight) {
alert(pwidth);
_img.css("width", pwidth).css("height", pwidth / iwidth * iheight);
_img.css("margin-top", (pheight - pwidth / iwidth * iheight) / 2 + "px");
} else {
_img.css("width", pheight / iheight * iwidth).css("height", pheight);
_img.css("margin-left", (pwidth - pheight / iheight * iwidth) / 2 + "px");
}
} else {
_img.css("margin-left", (pwidth - iwidth) / 2 + "px");
_img.css("margin-top", (pheight - iheight) / 2 + "px");
}
});
};

})(jQuery);


使用
页面代码:

<div class="mytest">
<ul>
<li>
<img src="Images/green.png" />
</li>
<li>
<img src="Images/login.gif" />
</li>
</ul>
</div>

函数调用:

<script type="text/javascript">
$(function () {
$('.mytest ul li').imgAutoSize();
});
</script>


注意事项:

1、".mytest ul li“是图片的容器

2、li要定义大小,且要加属性overflow:hidden;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: