2014-10-11 182 views
0

我有一個jQuery函數,它檢查子圖像高度的值,然後將父級高度設置爲最小圖像高度的值,然後添加overflow: hidden以避免溢出。計算返回多個值

我執行document.ready事件的功能,但是我收到了奇怪的結果。我將獲得HTMLobjectHeight,0,未定義或頁面加載的正確值。爲什麼這是變化的?它是在圖像加載之前發射的嗎?我有

function setContainHeight() 
{ 
    var container = $('.com-background'); 
    var imgs = $('.com-background img'); 
    var smallestImg = imgs[0]; 
    $(imgs).each(function() 
    { 
     if ($(this).height() < $(smallestImg).height()) 
      smallestImg = $(this).height(); 

    }); 

    container.height(smallestImg); 
    container.css("overflow", "hidden"); 
}; 

的另外一個問題是,當我添加此功能可將window.resize事件也觸發對頁面加載,並給出了一個不確定的結果。

HTML

<div class="com-background" style="height: 434px; overflow: hidden;"> 
    <h1 class="community_title">Sun Lakes</h1> 
    <img width="250" height="167" src="http://192.168.33.10.xip.io/wp-content/uploads/2013/04/Ocotillo-lake-e1404789921289.jpg" class="wp-post-image" alt="Ocotillo - lake" style="display: block; z-index: 1;"> 
    <img width="250" height="188" src="http://192.168.33.10.xip.io/wp-content/uploads/2013/04/Resort-e1404789892490.jpg" class="attachment-post-secondary-image-thumbnail active" alt="Resort" style="z-index: 3; opacity: 0.988634061784097;"> 
    <img width="837" height="378" src="http://192.168.33.10.xip.io/wp-content/uploads/2014/05/homestead-error.png" class="attachment-post-tert-image-thumbnail" alt="homestead-error" style="z-index: 2;"> <div class="numeric_search"> 
</div> 

SASS/CSS

.com-background 
{ 
    width: 100%; 
    position: relative; 
    img 
    { 
     z-index: 1; 
     position: absolute; 
     top: 0; 
     left: 0; 
     width: inherit; 
     max-width: 100%; 
     height: auto; 
    } 
} 
+0

安置自己相關的HTML和CSS了。 – akinuri 2014-10-11 23:09:38

+0

請顯示呈現的HTML,而不是PHP,除非您認爲PHP是相關的。 – 2014-10-11 23:23:07

回答

0

爲了確保圖像甲肝Ë被加載,啓動一個$(window).load事件偵聽器

我還用Math.min獲得最低圖像高度

$(window).on("load resize", function(event) { 

    // find container 
    var container = $(".com-background"); 

    // get image heights in an array 
    var heights = container.find("img").map(function(idx, elem) { 
    return $(elem).height(); 
    }).get(); 

    // get the minimum height 
    var minimum = Math.min.apply(null, heights); 

    // set container height and overflow property 
    container.height(minimum).css({overflow: "hidden"}); 
}); 
+0

未捕獲的TypeError:不能使用'in'運算符在undefined中搜索'height' – Chris 2014-10-11 23:51:22

+0

不錯,效果很好。現在我將它解壓縮到一個函數中,以便我可以使用resize事件。除非你認爲有更好的方法來改變'window.resize'上的容器大小嗎? – Chris 2014-10-11 23:56:13

+0

@Chris,我鼓勵你分解事件監聽器,但你可以簡單地使用'$(window).on(「load resize」,fn);'附加到這兩個事件。我已經更新了我的答案。 – naomik 2014-10-12 00:05:00

0

如果你想獲得的所有圖像的高度,你需要確保所有的圖像被下載並準備使用...要當然,你需要使用$(窗口).load()而不是$(文件).read這樣的:

$(window).load(function() { 
    setContainHeight(); 
    $(window).resize(setContainHeight); 
});