js/css实现图片等比裁切不变形显示

技术探讨  2018-04-26 13:26   8138 js css 图片等比显示

使用css或者js让图片铺满上层容器(div),超出部分等比例裁剪不变形或隐藏


方式一:

图片加载时使用js根据进行等比缩放,动态设置img的width/height属性


// 动态设置width/height
function scalingImg(obj)
{
    var $this = $(obj);
    var imgWidth  = $this.width();
    var imgHeight = $this.height();
    var parent    = $this.parent();
    var containerWidth  = parent.width();
    var containerHeight = parent.height();
    var containerRatio = containerWidth / containerHeight;
    var imgRatio = imgWidth / imgHeight;
    if (imgRatio > containerRatio)
    {
        var imgSetHeight = containerHeight;
        var imgSetWidth  = imgSetHeight * imgRatio;
    } else if (imgRatio    
   


方法二:

css3特殊样式实现

不要怀疑,你没有看错,就是这样一行简单的代码;请自行百度:object-fit:cover 效果

* 部分浏览器可能不支持


效果对比:


开始效果

blob.png

最终效果

blob.png

注:转载请注明出处为http://www.sandbean.com/article/57.html。

沙豆网 站长

追求卓越,奋斗不息!

167
文章
8810
点赞

更多文章