计算元素的未来高度

时间:2014-07-08 14:29:47

标签: javascript html css html5 css3

我的目的是使用CSS3动画,当子div扩展时,元素高度的转换。

<div id="container">
  <div id="content"> 
    <span>Small Conent</span>

    <div id="big">
      <p>
         This is way bigger content, will be visible after you have clicked the
         "Expand" button.
      </p>
      <p>It should animate up to the correct position.</p>
    </div>
  </div>

  <button id="expand">Expand</button>
</div>

我使用max-height想出了这个黑客。但是有一些问题:

  • 最大高度必须为值
  • 动画将根据max-height给定的值开始和停止,因此如果您插入像2000px这样的疯狂值,动画会有很长的延迟。

为了更好地说明问题,我创建了一个小提琴:http://jsfiddle.net/egDsE/3/

获得精确动画的唯一方法是插入正确的max-height值。

我的目的是使用JavaScript(和仅限JavaScript)计算一旦孩子扩展后父母的身高。但是,当然,我需要在实际转换发生之前计算它。

这可能吗?只有纯粹的JS。

3 个答案:

答案 0 :(得分:1)

实际上,你不需要做所有的克隆和东西...只需给元素高度自动,检查大小并将高度设置回0.它会发生得如此之快浏览器没有机会重新绘制。

现在,这就像一个魅力,但事实是,之后立即在Javascript中设置高度将导致转换失败。我只是在它周围抛出100毫秒超时然后它工作正常。

<强>使用Javascript:

document.getElementById('expand').addEventListener('click', function () {
    var el = document.getElementById('big');
    if (!el.className) {
        el.className = 'expanded';
        document.getElementById('expand').innerHTML = 'Retract';
        var elH = getHeight(el);
        window.setTimeout(function() {
            el.style.height = elH+'px';
        }, 100);
    } else {
        el.className = '';
        el.style.height = '0';
        document.getElementById('expand').innerHTML = 'Expand';
    }
});

function getHeight(el) {
    el.style.height = 'auto';
    elHeight = el.offsetHeight;
    el.style.height = '0';
    return elHeight;
}

<强> CSS:

#container {
    border: 1px solid gray;
    padding: 20px;
}
#big {
    overflow: hidden;
    height: 0;
    transition: height 0.5s ease-in-out;
    -webkit-transition: height 0.5s ease-in-out;
    -moz-transition: height 0.5s ease-in-out;
    -o-transition: height 0.5s ease-in-out;
}

HTML:您的标记没有变化

<div id="container">
    <div id="content"> <span>Small Conent</span>

        <div id="big">
            <p>This is way bigger content, will be visible after you have clicked the "Expand" button.</p>
            <p>It should animate up to the correct position.</p>
        </div>
    </div>
    <button id="expand">Expand</button>
</div>

DEMO

答案 1 :(得分:0)

我已经用Bartdude的评论中提出的解决方案更新了小提琴,尽可能优化它的性能。

http://jsfiddle.net/egDsE/5/

var calculateHeight = function(e) {
    var outside = document.getElementById('outside');
    var clone = e.cloneNode(true);
    outside.appendChild(clone);
    var elHeight = outside.offsetHeight;
    outside.removeChild(clone);

    return elHeight;
}

外部div有非常基本的css:

#outside {
    position: absolute;
    top: -1000;
    left: -1000;
}

如果涉及图像,我不推荐这种解决方案,它们会显着减慢操作速度。

答案 2 :(得分:0)

不是那个人,但如果你不想那么强大并且得到这个功能我会使用LESS