根据具有绝对位置的子div的高度更改父div的高度

时间:2013-11-07 06:24:53

标签: jquery css html

我有一个简单的幻灯片,用于翻阅社区网站的广告。我是jquery的新手,所以我不确定如何根据jquery下一个拉出的子div来改变父div的高度。请参阅下面的jsfiddle以获取我的代码。

HTML:

<div class="slideshow" id="ads_slideshow">
  <div id="slide1" class="slide">
    <p>Test Advertisement</p>
    <p>Just testing advertisements</p>
  </div>
  <div id="slide2" class="slide">
    <p>Test Ad 3</p>
    <p>One more test ad, just for clarity.</p>
  </div>
</div>

CSS:

.slideshow{ position: relative; border: 1px solid #000; }
#slide1, #slide2{ position: absolute; }

Jquery的:

$(function () {
    $('.slideshow div').hide();
    $('.slideshow div:first-child').show();
    setInterval(function () {
        $('.slideshow div:first-child').fadeOut(500)
            .next('div').fadeIn(500)
            .end().appendTo('.slideshow');
    },
    2000);
});

Jsfiddle:http://jsfiddle.net/us3m9/4/

2 个答案:

答案 0 :(得分:0)

place this code :
-------------------------------

 $(function () {
     // height of the div
     var ht = $(".slideshow .slide").height();
     $(".slideshow").css("height",ht);

      $('.slideshow div').hide();
      $('.slideshow div:first-child').show();
      setInterval(function () {
        $('.slideshow div:first-child').fadeOut(500)
        .next('div').fadeIn(500)
        .end().appendTo('.slideshow');
         // height of the div
          var ht = $(".slideshow .slide").height();
         $(".slideshow").css("height",ht);         

      },
    2000);
}); 

js fiddle:http://jsfiddle.net/us3m9/7/

答案 1 :(得分:0)

这就是我的所作所为:

基本上,我采用了当前显示的幻灯片的高度,并将.slideshow的高度设置为该高度。

http://jsfiddle.net/8fTfX/

jQuery的:

$(function () {
    $('.slideshow div').hide();
    $('.slideshow div:first-child').show();
    $('.slideshow').height($('.slideshow div:first-child').height())
    setInterval(function () {
        $('.slideshow div:first-child').fadeOut(500)
            .next('div').fadeIn(500)
            .end().appendTo('.slideshow');
        $('.slideshow').height($('.slideshow div:first-child').height())
    },
    2000);
});

CSS :(添加转换,因为为什么不呢?)

.slideshow {
    position: relative;
    border: 1px solid #000;
    transition: height 500ms;
}
#slide1, #slide2 {
    position: absolute;
}