簡體   English   中英

使用jQuery使img填充容器寬度/高度

[英]Make img fill container width/height with jQuery

我想做一些像背景大小的東西:封面,但我不關心圖像的居中,我只是想讓它適合整個容器。

我決定通過將圖像置於容器中心並檢查圖像是否有邊距來做到這一點。 如果圖像有右邊距,那么它需要寬度:100%和高度:自動否則高度:100%和寬度:自動;

這一切都很好,直到我在Firefox下測試它。 問題是$(this).css("margin-top")在除Firefox之外的所有瀏覽器中返回一個數字。 Firefox返回“auto”。 我嘗試用.offset.top替換margin-top ,但是它返回了整個頁面元素的偏移量,而不是它最接近的相對父級。

這是我的代碼:

 $("aside .img-container").each(function() { if ($(this).find("img").offset().top >= 0) { // if image has margin-top make it height 100% $(this).addClass("full_height"); } else { $(this).removeClass("full_height"); } if ($(this).find("img").offset().left > 0) { $(this).removeClass("full_height"); } }) 
 aside .img-container { position: relative; width: 25%; height: 0; padding-bottom: 25%; display: inline-block; float: left; } aside .img-container img { position: absolute; top: 0; right: 0; bottom: 0; left: 0; width: 100%; margin: auto; } aside .full_height img { width: auto !important; height: 100% !important; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <aside> <div class="img-container"> <img src="http://placehold.it/50x50" alt="" title=""> </div> <div class="img-container"> <img src="http://placehold.it/50x50" alt="" title=""> </div> <div class="img-container"> <img src="http://placehold.it/50x50" alt="" title=""> </div> <div class="img-container"> <img src="http://placehold.it/50x50" alt="" title=""> </div> <div class="img-container"> <img src="http://placehold.it/50x50" alt="" title=""> </div> <div class="img-container"> <img src="http://placehold.it/50x50" alt="" title=""> </div> <div class="img-container"> <img src="http://placehold.it/50x50" alt="" title=""> </div> <div class="img-container"> <img src="http://placehold.it/50x50" alt="" title=""> </div> <div class="img-container"> <img src="http://placehold.it/50x50" alt="" title=""> </div> <div class="img-container"> <img src="http://placehold.it/50x50" alt="" title=""> </div> <div class="img-container"> <img src="http://placehold.it/50x50" alt="" title=""> </div> <div class="img-container"> <img src="http://placehold.it/50x50" alt="" title=""> </div> </aside> 

我的問題是:是否有類似於.offset().top的函數返回圖像和容器之間的實際長度,因為有很多圖片,如果我必須手動計算,我擔心它會變成太遲鈍了。

我也對其他建議持開放態度。

編輯:添加了html。

是否存在類似於.offset()。top的函數,它返回圖像和容器之間的實際長度

.offset獲取整個文檔的坐標; .position然后獲取與元素的“偏移父元素”相關的位置。

偏移父元素是第一個以某種方式定位的祖先元素(因此CSS position值與默認static不同。)由於img-container元素相對定位,它們構成了圖像內部的偏移父元素。

暫無
暫無

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

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