使用jQuery来调整父元素的高度以匹配它的可见子元素的高度 [英] Using jQuery to adjust a parent element's height to match it's visible child's height

查看:137
本文介绍了使用jQuery来调整父元素的高度以匹配它的可见子元素的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

由于某些原因,我的代码不工作。每当 #container 元素调整大小时,函数运行并且 来调整 #main 的高度与可见幻灯片的高度相同。

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.

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

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

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:

JavaScript:

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


推荐答案

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

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

这篇关于使用jQuery来调整父元素的高度以匹配它的可见子元素的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆