3

我正在尝试为可扩展列表制作动画,但无法正确显示列表。没有正确显示动画效果列表(展开/折叠)。要折叠我正在使用的列表ul.style.visibility = "hidden"; ul.style.height = "0px";。没有动画效果,如果看起来不错,请列出:

正确显示的无序列表.

黑色边框位于 UL 元素上。我正在使用以下 Javascript 代码来扩展列表:

var from = 0; //The height
ul.style.height = "auto";  //set height to auto to get actual height
var to = ul.offsetHeight; //get height
ul.style.height = "0px";
ul.style.visibility = "visible";
ul.style.overflow = "hidden";

var start = new Date().getTime(),
    timer = setInterval(function() {
        var step = Math.min(1,(new Date().getTime()-start)/400);
        ul.style.height = (from+step*(to-from))+"px";
        if( step == 1) clearInterval(timer);
    },20);
//Expand List
ul.style.overflow = "inherit";
ul.style.height = "auto";
ul.style.visibility = "inherit";

ul在代码中是对ul当前正在扩展的无序列表中的元素的引用。

但是在使用此代码对展开行为进行动画处理后,外部ul元素的宽度不会随着内部ul元素的展开而改变。然而动画工作正常,但列表看起来像这样:

显示不正确的无序列表

//ul.style.height = (from+step*(to-from))+"px";当我从中注释掉时setInterval,列表正在正确显示(但没有动画效果)。

您能否指出错误,为什么外部宽度不ul随内部扩展而变化ul

4

1 回答 1

2

间隔结束时它无法正确显示的原因是因为您在间隔甚至运行其第一个间隔之前将“auto”分配给 ul.style.height。您应该在间隔结束时执行此操作:

timer = setInterval(function() {
    var step = Math.min(1,(new Date().getTime()-start)/400);
    if (1 === step) {
        ul.style.height = "auto";
        clearInterval(timer);
    } else {
        ul.style.height = (from+step*(to-from))+"px";
    }
},20);
于 2013-08-16T12:43:24.670 回答