html图片自适应裁剪,图片自适应裁剪(background-size:cover)

HTML

![](http://upload-images.jianshu.io/upload_images/1288413-363a440b208cf501.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

CSS

.img-container {

width: 100px;

height: 80px;

overflow: hidden;

float: left;

}

.img-container > img {

position: relative;

display: block;

max-width: none;

}

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();

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值