【问题标题】:Can't set elements height to its scrollHeight?不能将元素高度设置为其滚动高度?
【发布时间】:2013-05-22 19:06:43
【问题描述】:

由于某种原因,我无法制作平滑的 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

我也尝试将它设置为最大高度,但我仍然无法让它再次展开。如果没有任何 javascript 插件,我将如何做到这一点?

【问题讨论】:

    标签: javascript expand contract


    【解决方案1】:

    你错过了+"px"。使用style.height时需要设置单位(empx%等)。因为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

    【讨论】:

      【解决方案2】:

      我让它在 Chrome 中正常工作。 当我将“溢出”更改为“滚动”时的 IE。

      【讨论】:

        猜你喜欢
        • 2017-03-23
        • 1970-01-01
        • 2013-09-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-08
        • 1970-01-01
        • 2011-06-27
        相关资源
        最近更新 更多