簡體   English   中英

圖片無法正確調整為div的高度

[英]Image won't correctly adjust to the height of a div

我正在嘗試將圖像的高度設置為相鄰div的高度。

問題是,即使使用JavaScript抓取div的高度並使用它來設置圖像的高度,最后一個<p>元素也會出現在圖像下方。

 $("#here").find('img').css("height", $(".text").outerHeight()); 
 img { float: left; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="here"> <img src="https://images-na.ssl-images-amazon.com/images/M/MV5BMzg2Mjg1OTk0NF5BMl5BanBnXkFtZTcwMjQ4MTA3Mw@@._V1_SX300.jpg" alt="RED"> <div class="text"> <h2>Movie: RED</h2> <p>When his peaceful life is threatened by a high-tech assassin, former black-ops agent Frank Moses reassembles his old team in a last ditch effort to survive and uncover his assailants.</p> <p>Movie Categories Action, Comedy, Crime</p> <p>111 min long</p> <p>Some actors were Bruce Willis, Mary-Louise Parker, Heidi von Palleske, Karl Urban</p> <p>Rated: PG-13</p> </div> <br> <input type="submit" value="Add"> </div> 

您可以通過單擊提交按鈕在http://thecodesee.pe.hu/重現該問題。


這是我想要的結果:

在此處輸入圖片說明

這是當前的樣子:

在此處輸入圖片說明

試試這個解決方案。

$.ajax({
         type: "POST",
         url: "search.php",
         success: function(data) {
            $("#here").css("display", "block");
            $("#here").html(data).promise().done(function() {
               $("#here").find('img').css("height", $(".text").outerHeight());
               var $img = $("#here").find('img');

                $img.on('load', function() {
                    $("#here").find('img').css("height", $(".text").outerHeight());
                });
            });

     }
  });

僅在頁面加載時或僅在調用函數時調整圖像大小。 我相信您必須編寫一個window.onresize()事件以根據布局不斷更改圖像大小。

$(document).ready(function(){
            window.onresize = function(){
            $("#here").find('img').css("height", $(".text").outerHeight());     
            }

        });

但是,這並不適合首次加載。 div似乎是在獲取大小后渲染的。 您可能希望通過使用.ready()來確保該div在您獲取externalHeight()之前已被渲染。

您可以使用CSS簡單的CSS代碼對其進行修復; 通過調整寬度尺寸,例如:

 img {
  float: left;
  width: 25%;
}
.text {

  width : 75%;
}

暫無
暫無

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

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