您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

使图像完全填充div而无需拉伸

使图像完全填充div而无需拉伸

这是一种方法,从以下HTML开始:

<div class="container portrait">
    <h4>Portrait Style</h4>
    <img src="http://placekitten.com/150/300">
</div>

和CSS:

.container {
    height: 300px;
    width: 240px;
    background-color: red;
    float: left;
    overflow: hidden;
    margin: 20px;
}
.container img {
    display: block;
}

.portrait img {
    width: 100%;
}
.landscape img {
    height: 100%;
}

当您将图像定向为人像时,需要将宽度缩放到100%。相反,当图像为横向时,您需要缩放高度。

不幸的是,CSS中没有针对图像长宽比的选择器组合,因此您不能使用CSS来选择正确的缩放比例。

另外,由于图像的左上角固定在包含块的左上角,因此您没有简单的方法来使图像居中。

您可以使用以下jQuery操作来根据图像的纵横比确定要设置的类。

$(".container").each(function(){
    // Uncomment the following if you need to make this dynamic
    //var refH = $(this).height();
    //var refW = $(this).width();
    //var refRatio = refW/refH;

    // Hard coded value...
    var refRatio = 240/300;

    var imgH = $(this).children("img").height();
    var imgW = $(this).children("img").width();

    if ( (imgW/imgH) < refRatio ) { 
        $(this).addClass("portrait");
    } else {
        $(this).addClass("landscape");
    }
})

对于中的每个图像.container获取其高度和宽度,进行测试width<height,然后设置适当的类。

另外,我添加一个检查,以考虑到包含块的长宽比。以前,我隐式地假定了正方形视图面板。

其他 2022/1/1 18:18:55 有532人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶