簡體   English   中英

如何為具有完整(100%)寬度和未知高度的圖像設置樣式,使其不會彈出

[英]How do I style an image with full (100%) width and unknown height so it doesn't pop

我正在建立一個大部分圖像全出血的網站,也就是寬度:100%。 我有一個問題,圖像的高度為0,直到加載,這導致網站的元素跳了很多。

  • 我不能把它留空,因為它在加載之前是0。
  • 如果我將高度設置為像素值,則無法正確縮放。
  • 我無法將其設置為100%,因為它使用包含元素的高度。

我正在嘗試做什么? 我可以想辦法在第一次加載圖片后使用javascript解決這個問題,但看起來並不優雅。

救命!

<img src="http://lorempixel.com/1280/640/cats/1" id="auto" />
<p>This text will get pushed down after load starts</p>
<img src="http://lorempixel.com/1280/640/cats/2" id="fixed" />
<p>This text will get pushed down after load starts</p>
<img src="http://lorempixel.com/1280/640/cats/3" id="percentage" />
<p>This text will get pushed down after load starts</p>

img { width:100%; }
#auto { height: auto; }
#fixed { height: 640px; }
#percentage { height: 100%; }

的jsfiddle

你能做的最好的事情就是有一個包裝div元素,它與圖像的寬高比相匹配。

如下所示:

HTML

<div class="image-wrapper">
<img src="http://lorempixel.com/1280/640/cats/1" />
</div>
<p>This text will get pushed down after load starts</p>
<div class="image-wrapper">
<img src="http://lorempixel.com/1280/640/cats/2" />
</div>
<p>This text will get pushed down after load starts</p>
<div class="image-wrapper">
<img src="http://lorempixel.com/1280/640/cats/3" />
</div>
<p>This text will get pushed down after load starts</p>

CSS

.image-wrapper {
    position:relative;
    height:0;
    padding-bottom:50%; /* aspect ratio of the image ( ( 640 / 1280 ) * 100% ; ) */
}
.image-wrapper > img {
    position:absolute;
    top:0;
    left:0;
    width:100%;
}

小提琴: http//jsfiddle.net/Varinder/m8dFM/1/

如果瀏覽器尚未下載圖像,並且您沒有在img標記中指定圖像的高度,則無法知道在頁面中為其保留的高度。

您可以做的最好的事情是在這些圖像上設置一個安全的min-height ,以至少在加載時最小化“pop”。

這里沒有解決方案。

但是,有可能的答案。

如果您加載了有關每個圖像的JSON有效負載信息,並使用了document.body.getBoundingClientRect().width ,那么您可以使用正文的寬度(或容器的寬度)和圖像的元數據來保留這么高的高度。

當然,您必須加載JSON作為您在網站上做的第一件事(或將其烘焙到頁面中,或將其保存為JS對象,在包含的文件中),並且您必須保存您打算使用的每個圖像的數據...

...而且,你可以顯示一個SVG(可以非均勻拉伸,或者可以縮放和letterboxed),而不是什么都不顯示,你可以在你的預期圖像上加載(將在JS中加載)然后,您可以將SVG的位置設置為絕對(在頁面中的同一點),並開始將其淡入背景中,同時在圖像中交叉淡化,這將附加到DOM,在SVG所在的空間中占領...

或者不是“彈出”,你可以將它們全部滑入或放大..​​....或者如果你想要真的很煩人,縮小......

對於你認為是一個簡單問題的東西來說,這可能有點過頭了......而且它很可能是。

可悲的事實是,沒有解決方案,但幸福的現實是,你可以解決稍微不同的問題,使初始問題看起來新穎。

暫無
暫無

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

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