如何设置相对于其自身高度的响应比例图像 - 而不是其宽度

时间:2015-11-04 20:38:15

标签: javascript css image height responsive-images

如何设置相对于其自身高度的响应比例图像 - 而不是其宽度?

只需设置......

img{
    width: auto;
    height: 100%;
}

没有为我的图像提供比例尺寸。

我该怎么做?

2 个答案:

答案 0 :(得分:1)

我发现唯一一致的解决方案是javascript one。

在除IE8之外的所有浏览器上都支持自然宽度和自然高度。 IE8还有一个解决方法。 (http://www.jacklmoore.com/notes/naturalwidth-and-naturalheight-in-ie/

如果你不介意使用jquery和下划线,你可以设置每个宽度。

$(window).load( function() {

    function imgWidth(){
        $("img").each( function(){
            nWidth = $(this)[0].naturalWidth;
            nHeight = $(this)[0].naturalHeight;
            nRatio = nWidth/nHeight;

            curHeight = $(this).height();
            $(this).css("width", curHeight*nRatio);
        });
    }
    imgWidth();

    var updateLayout = _.debounce( function(e) {
        imgWidth();
    }, 500);
    window.addEventListener("resize", updateLayout, false);
}

答案 1 :(得分:0)

在HTML / CSS中,图像处理变得愚蠢。直接在img上的高度标记在很多场景中被忽略,具体取决于div属性。我认为最简单的方法是创建一个div,将有问题的图像设置为背景。

.img-div {
height:x; width:x;
background:url(file/path/here.svg);
background-position:center;
background-size:auto 100%;

这是一个示范:https://jsfiddle.net/JTBennett/nukLf5m3/