无法将元素高度设置为其scrollHeight?

时间:2013-05-22 19:06:43

标签: javascript expand contract

由于某些原因,我不能制作一个平滑的div,当我点击一个按钮时,我试图让它扩展和收缩,但它不起作用。

使用Javascript:

function expandContract(id) {
    var object = document.getElementById(id);
    if (object.style.height != "0px") {
        object.style.height = "0px";
    } else {
        object.style.height = object.scrollHeight;  
    }
}

HTML:

<div id='test' style='overflow:hidden;'>
Test pest fest.
</div>
<button onClick='expandContract("test");'>Expand/Contract</button>

jsFiddle

我也试过设置它做max-height,但我还是不能让它再次展开。如果没有任何javascript插件,我该怎么做?

2 个答案:

答案 0 :(得分:1)

你错过了+"px"。使用em时,您需要设置一个单位(px%style.height等)。由于scrollHeight只为您提供了一个数值,因此在这种情况下您必须附加px的单位。

function expandContract(id) {
    var object = document.getElementById(id);
    if (object.style.height != "0px") {
        object.style.height = "0px";
    } else {
        object.style.height = object.scrollHeight+"px";  
    }
}

jsFiddle

答案 1 :(得分:0)

我让它在Chrome中工作,原样。 IE当我将'overflow'更改为'scroll'时。