javascript 保持背景图像的纵横比

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22571629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:23:59  来源:igfitidea点击:

Maintain aspect ratio of background-image

javascriptjqueryhtmlcss

提问by Patrick

I need to present images in a container using the CSS property background-image

我需要使用 CSS 属性在容器中显示图像 background-image

The problem here is that I need to present every image keeping the aspect ratio of it, and maximize the presentation of the image to the heightor widthof the image centered inside the container.

这里的问题是我需要呈现每个图像保持其纵横比,并最大限度地显示图像到容器内居中的图像heightwidth图像。

HTML:

HTML:

<div class="fotowind shadow"></div>


EDIT:

编辑:

Initial CSS properties of the .fotowindcontainer:

.fotowind容器的初始 CSS 属性:

.fotowind {
    overflow:hidden;
    margin-left:10px;
    background:#333;
    margin-bottom:5px;
    z-index:30;
    background-position: center center !important;
    background-repeat: no-repeat;
} 

Code to build the properties dynamically based in the size of the window - I need to resize the image keeping the ratio, even of some empty space as to remain on the sides:

根据窗口大小动态构建属性的代码 - 我需要调整图像大小以保持比例,即使是一些空白空间以保留在侧面:

jQuery:

jQuery:

windowWidth = $(window).width();
windowHeight = $(window).height();

if (windowWidth <= 1200 && windowWidth > 768 || windowHeight < 900)
{
    $('.fotowind').css('width', '650px').css('height', '425px');
}
else if (windowWidth > 1200 || windowHeight > 900)
{
    $('.fotowind').css('width', '950px').css('height', '650px');
}

if (windowWidth <= 768)
{
    $('.fotowind').css('width', '450px').css('height', '425px');
}

Resulting HTML:

结果 HTML:

<div class="fotowind shadow" style="background-image: url(http://localhost/AdPictures/25/2c/c2/4c/-9/77/1-/4b/77/-b/ff/a-/57/e5/10/2b/31/b1/7516_1_xl.jpg); background-size: 100%; width: 950px; height: 650px; background-position: 50% 50%; background-repeat: no-repeat no-repeat;"></div>

In some situations where an image has size 800x600, for example, I can't present it with this size, or when the image has 200x650, for example, it deforms to the container size.

800x600例如,在图像具有 size 的某些情况下,我无法以该大小显示它,或者当图像具有 时200x650,例如,它会变形为容器大小。

Example

例子

采纳答案by Mr. Alien

As I saw that you are already using jQuery, so I assume that you are open to jQuery solution, because, as I read your comment which says

正如我看到你已经在使用 jQuery,所以我假设你对 jQuery 解决方案持开放态度,因为,当我读到你的评论时

I want to center the background-imageif the viewport size exceeds the original image size, and if it's equal to or less than the real size, than you want a responsive background

background-image如果视口大小超过原始图像大小,并且等于或小于实际大小,我想居中,而不是您想要响应式背景

So here, I am using jQuery to detect the windows heightand widthand accordingly am resizing your background-image

所以在这里,我使用 jQuery 来检测窗口heightwidth并相应地调整你的background-image

Demo

Demo

$(window).on('resize', function() {
    if($(window).width() < 300) { //original idth of your background image
        $('div.fotowind').css('background-size', '100% auto');
    } else if($(window).height() < 300) { //original height of your background image
        $('div.fotowind').css('background-size', 'auto 100%');
    } else {
        $('div.fotowind').css('background-size', 'auto');
    }
});


There is no CSS solution as such because we don't have max-widthand max-heightfor background-sizeso if you are looking for a pure CSS solution, than you will need an absolutepositionedimgtag, with max-heightand max-widthdefined with a z-indexset to negative, but still you will face some issues regarding the element center positioning...

没有CSS解决方案等,因为我们没有max-widthmax-height用于background-size所以如果你正在寻找一个纯CSS的解决方案,比您将需要一个absolute定位img标签,与max-heightmax-width与定义z-index设置为负值,但你仍然会面临一些问题关于元素中心定位...



After you commented, you said that the images will be dynamic in dimensions, and the container will be fixed so..

在您发表评论后,您说图像将在维度上是动态的,并且容器将被固定,因此..

Here, now the code is completely compatible with your fixed widthcontainer elements.. you need to do nothing now and it's completely dynamic, also thanks to thisanswer which helped me to fetch the heightand widthof the image

在这里,现在代码与你的固定width容器元素完全兼容..你现在什么都不用做,它是完全动态的,也感谢这个答案帮助我获取图像的heightwidth

$(document).on('ready', function() {
    var image_url = $('div.fotowind').css('background-image'), image;

    // Remove url() or in case of Chrome url("")
    image_url = image_url.match(/^url\("?(.+?)"?\)$/);

    if (image_url[1]) {
        image_url = image_url[1];
        image = new Image();
        image.src = image_url;
    }

    // just in case it is not already loaded
    $(image).load(function () {
        imgwidth = image.width;
        imgheight = image.height;

        if($('div.fotowind').width() < imgwidth) {
            $('div.fotowind').css('background-size', '100% auto');
        } else if($('div.fotowind').height() < imgheight) {
            $('div.fotowind').css('background-size', 'auto 100%');
        } else {
            $('div.fotowind').css('background-size', 'auto');
        }
    });
});

Few demos to illustrate the above code in action...

很少有演示来说明上述代码的实际操作......

Demo 1(Where image size > than the elements size)

Demo 1(其中图像大小 > 比元素大小)

Demo 2(Where container size > image size)

Demo 2(其中容器大小 > 图像大小)

Demo 3(Where image height > container height)

Demo 3(其中图像高度 > 容器高度)

Demo 4(Where image height > container height [2])

Demo 4(其中图像高度 > 容器高度 [2])

Demo 5(Where image width > container width)

Demo 5(其中图像宽度 > 容器宽度)

回答by dippas

You can use background-size: cover

您可以使用 background-size: cover

body {
  margin: 0
}
.fotowind {
  background: url(//placehold.it/400) fixed no-repeat center / cover;
  min-height: 100vh /*demo purposes*/
  
}
<div class="fotowind shadow">&nbsp;</div>

See more info on thisarticle

查看更多信息文章

回答by pasine

I tried to propose two different solution, one with a background-image and the other one with an image tag.
Here is the code:

我尝试提出两种不同的解决方案,一种带有背景图像,另一种带有图像标签。
这是代码:

HTML

HTML

<div class="container">
  <img src="https://upload.wikimedia.org/wikipedia/commons/e/e2/Mei_Foo_Station_2.JPG" alt="foo" />
  <div class="bg"></div>
  <div class="bg bg_h_s"></div>
  <div class="bg bg_h_m"></div>
  <div class="bg bg_h_l"></div>
  <div class="bg bg_w_s"></div>
  <div class="bg bg_w_m"></div>
  <div class="bg bg_w_l"></div>
</div>

CSS

CSS

.container {
  text-align: center;
  background-color: grey;
}

.bg {
  background: url(https://upload.wikimedia.org/wikipedia/commons/e/e2/Mei_Foo_Station_2.JPG) no-repeat center center blue;
  -webkit-background-size: contain;
  background-size: contain;
  height: 480px
}

img, .bg {
  width:100%;
  max-width:640px;
  margin: 30px auto;
}

.bg_h_s {
  height:100px;
}

.bg_h_m {
  height:200px;
}

.bg_h_l {
  height:300px;
}

.bg_w_s {
  width:200px;
}

.bg_w_m {
  width:400px;
}

.bg_w_m {
  width:600px;
}

Here is the working codepen

这是工作代码笔