图像的最佳适合显示

时间:2019-04-27 23:44:45

标签: javascript display

css / html5是否可以使图像最佳地适合视口,从而不会发生裁剪?

我希望能得到上述解决方案。这是在代码中完成的方式:

如果图像的纵横比(H / W)大于显示屏,则图像的CSS将为height:100%,width:auto;

如果图像的高宽比(H / W)小于显示屏,则图像的css将为height:auto,width:100%

这似乎需要大量工作,有没有更简单的解决方案?

山姆

3 个答案:

答案 0 :(得分:0)

尝试一下,看看它是否适合您。 vh单位表示视口高度。

.that-image {
  display: block;
  height: 100vh;
  position: absolute;
}

有一个相应的宽度单位vw

答案 1 :(得分:0)

您可以将is设置为div背景,并设置这种样式

    <div class='my-image.jpg'></div>
    .my-image {
        background-repeat: no-repeat;
        background-position: center;
        background-size: cover;
        text-align: center;
        height: 100vh;
        width: 100vw;
        background-image: url("https://images.pexels.com/photos/457882/pexels-photo-457882.jpeg");
    }

答案 2 :(得分:0)

这就是我要避免扭曲图像长宽比的方法:

function fitImage() { // Optimally fit an image to the viewport
    var width = $(this).width();    // Current image width
    var height = $(this).height();  // Current image height 

    var viewportHeight = $(window).height(); // The viewport height/width
    var viewportWidth = $(window).width(); 

    var aspectImage = parseFloat(height)/parseFloat(width); // Need Floating point
    var aspectViewport = parseFloat(viewportHeight)/parseFloat(viewportWidth);

    if (aspectImage > aspectViewport) { // height:100%;width:auto;
        $(this).width("auto"); // Image aspect ratio > Viewport 
        $(this).height("100%");
    } else { // height:auto;width:100%
        $(this).width("100%"); // Image aspect ration <= Viewport
        $(this).height("auto");
    }

}