img及父元素(容器)实现类似css3中的background-size:contain / background-size:cover
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<style>
.item{
width:600px;
height:500px;
float:left;
background-color:black;
}
body:after{
content:"";
display:block;
clear:both;
}
</style>
</head>
<body>
<div class="item"><img src="img/720x480.jpg" /></div>
<div class="item"><img src="img/snack.jpg" /></div>
<script type="text/javascript" src="js/jquery.js"></script>
<script>
$(function () {
/*
定义jQuery插件 imageSize
使用方式
$("容器").imageSize("contain") 或 $("容器").imageSize("cover")
*/
$.fn.imageSize = function (type) {
this.each(function () {
var This = $(this),
$img = This.find(">img"),
box_width = This.width(),
box_height = This.height();
getRealImageSize($img.attr("src"), function (w, h) {
if (type == "contain") {//跟background-size:contain一样效果
if (box_width / box_height <= w / h) {
$img.css({ "100%", height: "auto", paddingTop: ((box_height - box_width * h / w) / 2) + "px" });
}
else {
$img.css({ height: "100%", "auto", paddingLeft: ((box_width - box_height * w / h) / 2) + "px" });
}
} else if (type == "cover") {//跟background-size:cover一样效果
This.css("overflow", "hidden");
if (box_width / box_height <= w / h) {
$img.css({ "auto", height: "100%" });
}
else {
$img.css({ height: "auto", "100%" });
}
} else {//无效果
This.css("overflow", "hidden");
}
});
});
//引用自http://www.zhihu.com/question/28733200
function getRealImageSize(url, callback) {
var img = new Image();
img.src = url;
// 如果图片被缓存,则直接返回缓存数据
if (img.complete) {
callback(img.width, img.height);
} else {
// 完全加载完毕的事件
img.onload = function () {
callback(img.width, img.height);
}
}
}
};
/*
开始调用插件
*/
$(".item").imageSize("contain");
});
</script>
</body>
</html>