HTML
<div class="img-container">
![](http://upload-images.jianshu.io/upload_images/1288413-363a440b208cf501.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
</div>
CSS
<style>
.img-container {
width: 100px;
height: 80px;
overflow: hidden;
float: left;
}
.img-container > img {
position: relative;
display: block;
max-width: none;
}
</style>
JS
//----UI object init
(function (window, $) {
//check Zepto
if (!$) {
throw 'please include zepto first.';
}
window.UI = {
boot: [],
$body: $('body'),
$doc: $(document),
$win: $(window),
$content: $('body').children('.app').length ? $('body').children('.app') : $('body'),
init: function () {
this.boot.forEach(function (fn) {
if ($.isFunction(fn)) {
fn();
}
});
}
};
//---组件
window.Component = function (fn) {
var UI = window.UI;
if (!UI) return;
fn(UI, $);
};
})(window, Zepto);
//-----图片自适应容器
window.Component(function (UI, $) {
UI.imageAdapt = function ($imgContainer) {
var $img = $imgContainer.children('img');
$img.on('load', function () {
var rate = $img.width() / $img.height();
var parentWidth = $imgContainer.width();
var parentHeight = $imgContainer.height();
var parentRate = parentWidth / parentHeight;
if ($img.length > 0 && rate > parentRate) {
//----horizental cut
$img.height(parentHeight);
$img.css("right", "50%");
$img.css("margin-right", "-" + $img.width() / 2 + "px");
} else {
//----vertical cut
$img.width(parentWidth);
$img.css("top", "50%");
$img.css("margin-top", "-" + $img.height() / 2 + "px");
}
});
}
UI.boot.push(function () {
$('.img-container').each(function () {
UI.imageAdapt($(this));
});
$(window).resize(function () {
$('.img-container').each(function () {
UI.imageAdapt($(this));
});
});
});
});
//----初始化
window.UI.init();