jQuery:基于内容大小调整大小的动画容器

时间:2015-11-10 15:29:19

标签: javascript jquery jquery-ui jquery-animate containers

在这里,我尝试创建一个动画div容器,该容器会根据带动画的内容大小调整自身大小。问题在于不能容易地计算尺寸,这使得难以使用共同的建议。

我在下面的链接上重现了整个问题,我正在寻找一个提示来找到解决方案。

https://jsfiddle.net/csj78rgo/2/

我解决这个问题的首选方法是jQuery,jQuery-ui或Bootstrap JS。

HTML:

<div class="container">
    <div id="part1">
        <h3>TITLE</h3>
        <p>Some content</p>
        <p>Some content</p>
    </div>
    <div id="part2">
        <p>Some content</p>
    </div>
    <div id="part3">
        <p>Some content</p>
        <p>Some content</p>
    </div>
</div>

JS:

step = 0;
if (step==0) {
    $('#part1').show();
    $('#part2').hide();
    $('#part3').hide();
}  else if (step==1) {
    $('#part1').hide();
    $('#part2').show();
    $('#part3').hide();
} else if (step==2) {
    $('#part1').hide();
    $('#part2').hide();
    $('#part3').show();
}

CSS:

.container {
    border: 1px black solid
}

2 个答案:

答案 0 :(得分:0)

我会说使用类似于下面的逻辑;替换“$('#part1')。show();”逻辑。

$('#part1').show();
var containerHeight = $('#part1').height();
$('#part1').hide();

$('#part2').hide();
$('#part3').hide();

$('.container').animate({height: containerHeight + "px"}, 400, "linear", function() {
    $('#part1').fadeIn(100);
});

前3行是解决FireFox唯一的错误,它不会检测元素的高度,除非它是可见的。通过显示它,获得高度,然后隐藏它......它发生得如此之快,它不会在浏览器上显示,但你可以获得动画的高度。

animate有一个回调函数,只有在容器重新调整大小足以显示它之后才会显示新元素。

需要做一些调整才能完全按照自己的意愿行事,但是应该有足够的东西让你明白这一点。

答案 1 :(得分:0)

您不需要做任何想要调整容器大小的事情,一旦隐藏其中的内容,它就会自动调整大小。您可以使用jQuery&{39} .show().hide()duration参数来设置内容和动画内容。

&#13;
&#13;
var step = 0;
setInterval(function() {
  if (step==0) {
    $('#part1').show("slow");
    $('#part2').hide("slow");
    $('#part3').hide("slow");
  }  else if (step==1) {
    $('#part1').hide("slow");
    $('#part2').show("slow");
    $('#part3').hide("slow");
  } else if (step==2) {
    $('#part1').hide("slow");
    $('#part2').hide("slow");
    $('#part3').show("slow");
  }

  if(step++ == 3)
    step = 0;
}, 1000);
&#13;
.container {
  border: 1px black solid
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="container">
  <div id="part1">
    <h3>TITLE</h3>
    <p>Some content</p>
    <p>Some content</p>
  </div>
  <div id="part2">
    <p>Some content</p>
  </div>
  <div id="part3">
    <p>Some content</p>
    <p>Some content</p>
  </div>
</div>
&#13;
&#13;
&#13;

相关问题