计算一个元素未来的高度

Calculate the future height of a element

本文关键字:元素 未来 高度 一个 计算      更新时间:2023-09-26

我的意图是使用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>

我想出了这个hack,使用max-height。但是有几个问题:

  • max-height必须有一个值
  • 动画将根据max-height给定的值开始和停止,所以如果你插入一个疯狂的值,如2000px,动画将有很大的延迟。

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

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

我的目的是计算使用JavaScript(和JavaScript仅)什么高度的父将是一旦子扩展。当然,我需要在实际转换发生之前计算它。

这可能吗?

实际上,您不需要做所有的克隆和东西…只是给元素高度auto,检查大小并将高度设置为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: no changes to your markup

<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>
演示

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

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

如果涉及到图像,我不推荐这个解决方案,它们会显著降低操作速度。

不是那样的人但是如果你不想那么密集的话我会使用LESS