两个元素的平行动画,其中宽度为1取决于其他元素的最终宽度

时间:2013-09-01 14:37:29

标签: jquery jquery-animate

假设我们有两个div s,第二个div必须与第一个width一样宽。如果我刚刚获得第一个div并将第二个.css设置为width属性,则可行,因为第一个div的{​​{1}}已知。但是.animate,其未知。我必须等到第一个.animate运行。

Demo Fiddle

#a
{
    background-color: green;
}

#b
{
    background-color: red;
}

<span id="a">aaa aa a a a a a aa</span>
<br />
<span id="b">bbb</span>

$(document).ready(function()
{
    // this works, but I dont want this
    $('#b').width ($('#a').width());

    // and this WONT work, because widht of #a is not yet calculated    
    $('#b').animate({
        'width' : $('#a').width()
    }, 1500);
}

2 个答案:

答案 0 :(得分:1)

如果我完全理解你的问题,那么这比我之前在评论中发布的样本更接近你想要的内容。

step函数对于启用自定义动画类型或在动画发生时更改动画非常有用(根据当前width动态设置#b width #a,因为它也是动画的)。 now变量在每一步都会有#a的计算宽度。

$(document).ready(function() {
  $('#a').animate({
    'width': $('#c').width()
  }, {
    duration: 1500,
    queue: false,
    step: function(now, fx) {
      $('#b').animate({
        'width': now
      }, {
        duration: 2500,
        queue: false
      })
    }
  });
});
#a {
  background-color: green;
}
#b {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span id="c">Some very lengthy content</span>
<br/>
<span id="a">Some lengthy content</span>

<br/>
<span id="b">Some content</span>

答案 1 :(得分:0)

可能我也不明白问题,但希望你需要这样的代码:

HTML

<div id="firstDiv"></div>
<div id="secondDiv"></div>

CSS

#firstDiv
{
    width: 200px;
    height: 100px;
    background-color: Green;
}
#secondDiv
{
    width: 10px;
    height: 100px;
    background-color: red;
}

JQuery的

$(document).ready(function(){
    var firstWidth = "300px"
    $("#firstDiv").animate({width: firstWidth}, 1000)
    $("#secondDiv").animate({width: firstWidth}, 1000 );
});

Fiddle