简体   繁体   English

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

[英]How do I set a responsive proportional image that is relative to its own height – NOT its width

How do I set a responsive proportional image that is relative to its own height – NOT its width? 如何设置相对于自身高度而不是宽度的响应比例图像?

simply setting... 只需设置...

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

doesn't give me proportional dimensions for my image. 没有给我图像的比例尺寸。

How can I do that? 我怎样才能做到这一点?

I've found the only consistent solution was a javascript one. 我发现唯一一致的解决方案是JavaScript。

Introducing naturalWidth and naturalHeight.. supported on all browsers except IE8. 引入了除IE8之外的所有浏览器都支持的naturalWidth和naturalHeight..。 There is also a work around for IE8. IE8也有解决方法。 ( http://www.jacklmoore.com/notes/naturalwidth-and-naturalheight-in-ie/ ) http://www.jacklmoore.com/notes/naturalwidth-and-naturalheight-in-ie/

If you don't mind using jquery and underscore you could set each width like so. 如果您不介意使用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);
}

Image manipulation becomes stupidly convoluted in HTML/CSS. 在HTML / CSS中,图像处理变得令人费解。 The height tags directly on the img get ignored in a lot of scenarios, depending on div properties. 在很多情况下,取决于div属性,直接在img上的height标签将被忽略。 I think the simplest way is to create a div with the image in question set as the background. 我认为最简单的方法是使用有问题的图像作为背景来创建div。

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

Here's a demonstration: https://jsfiddle.net/JTBennett/nukLf5m3/ 这是一个演示: https : //jsfiddle.net/JTBennett/nukLf5m3/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM