开发者

Using jQuery to adjust a parent element's height to match it's visible child's height

开发者 https://www.devze.com 2023-03-24 13:48 出处:网络
I\'ve got a slideshow running in a container and need the height of the container to match the visible slide\'s height. Unfortunately the images are absolutely positioned and there\'s nothing I can do

I've got a slideshow running in a container and need the height of the container to match the visible slide's height. Unfortunately the images are absolutely positioned and there's nothing I can do about it. To deal with that, I'm using a little jQuery magic to take care of the same functionality.

For some reason, my code isn't working. Whenever the #container element is resized the function runs and is supposed to adjust #main's height to the same value as the visible slide's.

But, uh.. no bueno. Not showing any errors in my console. Thoughts?

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

Slideshow Plugin: 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://pay开发者_运维百科load.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);
});


I'd suggest using the plug-in's callback options, particularly the after:

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

Updated JS Fiddle demo.

References:

  • cycle() plug-in's 'callback' documentation/demonstration


Instead of running before or after the slideshows callback, this scales the image as the window resizes. Perfect!

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


I found this to work well:

$(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);
}); 

Where ".image-box" is the container for your images.

I also added this to my CSS for responsiveness:

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

}

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号