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

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();
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容