簡體   English   中英

如何設置相對於自身高度而非寬度的響應比例圖像

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

如何設置相對於自身高度而不是寬度的響應比例圖像?

只需設置...

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

沒有給我圖像的比例尺寸。

我怎樣才能做到這一點?

我發現唯一一致的解決方案是JavaScript。

引入了除IE8之外的所有瀏覽器都支持的naturalWidth和naturalHeight..。 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);
}

在HTML / CSS中,圖像處理變得令人費解。 在很多情況下,取決於div屬性,直接在img上的height標簽將被忽略。 我認為最簡單的方法是使用有問題的圖像作為背景來創建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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM