HTML
<!--LazyLoad Image-->
<div class="photo-wall">
<div class="img-container">
![](http://upload-images.jianshu.io/upload_images/1288413-1049f2b7def0fb5c.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
</div>
</div>
CSS
<style>
.img-container {
width: 220px;
height: 220px;
overflow: hidden;
}
.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-content').length ? $('body').children('.app-content') : $('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.Component(function (UI, $) {
UI.lazyLoadImage = function ($content) {
$('.img-container:not(.loaded)').each(function () {
var $imgContainer = $(this);
var $img = $imgContainer.children('img');
if ($img && $imgContainer.offset().top < $content.height() + $content.offset().top) {
$imgContainer.addClass('loaded');
var src = $img.attr('data-src');
$img.attr('src', src);
//----图片加载的进行自适应裁剪
$img.on('load', function () {
UI.imageAdapt($imgContainer);
});
}
});
};
UI.boot.push(function () {
//---滚动 加载
UI.$content.scroll(function () {
UI.lazyLoadImage(UI.$content);
});
UI.lazyLoadImage(UI.$content);
});
});
//---初始化
window.UI.init();