可扩展的无序列表动画,渲染问题

时间:2013-08-16 12:04:22

标签: javascript

我正在尝试为可扩展列表设置动画,但在正确显示列表时遇到问题。 没有动画效果列表正在正确显示(展开/折叠)。要折叠列表,我使用的是ul.style.visibility = "hidden"; ul.style.height = "0px";。如果没有动画效果,请列出是否正常:

Correctly displayed unordered list

黑色边框位于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元素的扩展而改变。但是动画工作正常,但列表看起来像这样:

Incorrectly displayed unordered list

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

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

1 个答案:

答案 0 :(得分:2)

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

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