使用jQuery调整父元素的高度以匹配其可见子元素的高度

时间:2011-07-30 08:33:50

标签: jquery css image resize height

我在容器中运行幻灯片,需要容器的高度与可见幻灯片的高度相匹配。不幸的是,图像是绝对定位的,我无能为力。为了解决这个问题,我正在使用一些jQuery魔术来处理相同的功能。

出于某种原因,我的代码无效。只要调整#container元素的大小,函数就会运行并且假设#main的高度调整为与可见幻灯片相同的值。

但是,呃..没有bueno。在我的控制台中没有显示任何错误。想法?

http://jsfiddle.net/danielredwood/2G4ky/3/

幻灯片插件:http://jquery.malsup.com/cycle/

HTML:

<div id="container">
  <div id="main" class="home" role="main">
      <img class="slide" src="http://payload.cargocollective.com/1/0/18788/1279362/452120_800_892531_800.jpg" />
      <img class="slide" src="http://payload.cargocollective.com/1/0/18788/1279362/452125_800_37eba7_800.jpg" />
      <img class="slide" src="http://payload.cargocollective.com/1/0/18788/1279362/452132_800_7dc0b6_800.jpg" />
  </div>
</div>

CSS:

#container {
    max-width:960px;
}
#main {
    max-width:780px;
    height:520px;
    margin:0 auto 40px;
    overflow:hidden;
    background:#ccc;
}
#main img {
    width:100%;
    height:auto;
}

JavaScript的:

$('.home').cycle({
    fx:'fade' 
});
$('#container').resize(function(){
      var child_height = $('.slide:visible').height();
      $('#main').css('height', child_height);
});

3 个答案:

答案 0 :(得分:3)

我建议使用插件的回调选项,尤其是after

$('.home').cycle({
    fx:'fade',
    after: function(){
        $('#main').css('height',$(this).outerHeight());
    }
});

Updated JS Fiddle demo

参考文献:

答案 1 :(得分:1)

在幻灯片回调之前或之后运行,而不是在窗口调整大小时缩放图像。完美!

$(window).resize(function() {
    $('#main').css('height',$('img.slide:visible').height());
});

答案 2 :(得分:0)

我发现这很好用:

$(window).load(function() {
var imageHeight = $(".image-box img").height();
$(".image-box img").parent().css('height', imageHeight);
});

$(window).resize(function() {
var imageHeight2 = $(".image-box img").height();
$(".image-box img").parent().css('height', imageHeight2);
}); 

其中“.image-box”是图片的容器。

我还将此添加到我的CSS中以获得响应:

.image-box img{
max-width: 100%;
height:auto !important;

}