2014-10-11 185 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); 
});