JavaScript实现Div折叠展开效果及定时器机制解析

作者:像素猫

时间:2026-10-29

浏览:511

本文通过实例展示如何使用JavaScript实现Div的折叠与展开效果,重点解析了style.display与style.visibility在获取offsetHeight时的差异,以及style.height带单位的特性。同时深入探讨了setTimeout的两种调用方式,并通过代码示例解释了异步回调导致的执行顺序问题,即alert('1')因定时器延迟最后输出。

文章目录

JavaScript实现Div折叠效果

本文通过具体实例,详细讲解如何利用JavaScript实现Div元素的折叠与展开(toggle)功能,供读者参考学习。

核心代码与HTML结构


<script type="text/javascript" language="javascript">
  function $(obj)
  {
  return document.getElementById(obj);
  }
  function ToggleDiv()
  {
  this.ToggleId='silder'; //被伸缩的对象ID
  this.ParentId='container'; //被伸缩的对象的父ID
  this.minHeight=1; //最小高度
  this.maxHeight=200; //最大高度
  this.speed=1; //伸缩速度
  this.offset=0.15; //偏移量
  this.load=function()
  {
   if($(this.ToggleId).style.display=='none') //如果是隐藏的就打开
   {
    StartToggle('open',this.ToggleId,this.ParentId,this.minHeight,this.maxHeight,this.speed,this.offset);
   }
   else //如果是打开的就隐藏
   {
     StartToggle('close',this.ToggleId,this.ParentId,this.minHeight,this.maxHeight,this.speed,this.offset);
   }
  }
  }
  function StartToggle(method,toggleid,parentid,minheight,maxheight,speed,offset)
  {
  if(typeof(method)!='string' || method.toLowerCase()=='')
  {
   method='open';
  }
  if(method.toLowerCase()=='open')
  {
   var addspeed=speed+offset;
   var openfun=function()
   {
    var originheight=$(toggleid).offsetHeight==0?1:$(toggleid).offsetHeight;
    var newheight=originheight+addspeed;
    addspeed=addspeed+offset;
    if(parseInt(newheight)<parseInt(maxheight))
    {    
     $(toggleid).style.height=newheight+'px';
     $(toggleid).style.display='block';
    }
    else if(parseInt(newheight)>=parseInt(maxheight))
    {
     $(toggleid).style.height=maxheight+'px';
     $(toggleid).style.display='block';
     $(parentid).innerHTML='收缩';
     window.clearInterval(addtimer);
    }
   }
   var addtimer=window.setInterval(openfun,100);
  }
  else if(method.toLowerCase()=='close')
  {
   var addspeed=speed+offset;
   var reducefunction=function()
   {
    var originheight=$(toggleid).offsetHeight;
    var newheight=originheight-addspeed;
    addspeed=addspeed+offset;
    if(parseInt(newheight)>parseInt(minheight))
    {
     $(toggleid).style.height=newheight+'px';
     $(toggleid).style.display='block';
    }
    else
    {
     $(toggleid).style.display='none';
     $(toggleid).style.height='1px';
     $(parentid).innerHTML='展开';
     window.clearInterval(reducetimer);
    }
   }
   var reducetimer=window.setInterval(reducefunction,100);
  }
  }
  function DoToggle(obj1,obj2)
  {
  var tog=new ToggleDiv();
  tog.ToggleId=obj1;
  tog.ParentId=obj2;
  tog.minHeight=5;
  tog.maxHeight=110;
  tog.speed=10;
  tog.offset=3;
  tog.load();
  }
</script>

具体的使用场景示例如下所示:


<div style="border:1px dashed blue;width:200px;">
  <h2 id="container" onclick="javascript:DoToggle('silder',this.id);" onmouseover="this.style.cursor='pointer';">展开</h2>
  <div id="silder" style="display:none">
  伸缩效果<br />
  伸缩效果<br />
  伸缩效果<br />
  伸缩效果<br />伸缩效果<br />
  伸缩效果<br />
  </div>
</div>

代码实现中包含部分冗余或重复逻辑。虽然可以进一步精简,但为了保持思路清晰,此处保留完整结构以便理解核心逻辑。

关键经验与属性差异

以下是本次开发练习中的关键经验总结:

1、当设置style.display为'none'与style.visibility为'hidden'时,读取对象的offsetHeight属性结果不同。若display为'none',offsetHeight返回0;若visibility为'hidden',则返回对象加载时的实际高度,例如108等数值。

2、style.height属性的值并非整型或Number类型,而是包含单位的字符串,例如"108px"而非单纯的"108";相比之下,offsetHeight返回的是纯数值108。

定时器机制与执行顺序

3、关于setTimeout与setInterval的使用细节:

这两个方法均支持两种调用形式,以setTimeout为例进行说明:

第一种方法:setTimeout(function, interval, args...)。第一个参数为函数名或匿名函数,第二个参数为时间间隔(毫秒),第三个及后续参数为传递给所调用函数的参数。示例如下:

setTimeout(function(){alert('1');},1000) 与 setTimeout(GetStr,1000,'McJeremy')。

第二种方法:setTimeout(object, function, interval)。第一个参数为调用对象,第二个参数为该对象中的方法名,第三个参数为时间间隔。

这里有一个值得注意的现象:


function a()
{
 setTimeout(function(){alert('1');},0);
 alert('2');
}

请推测以下代码的输出结果:

输出结果为21,而非12。这是因为JavaScript函数的执行遵循堆栈机制。由于alert('1')被setTimeout包裹,其执行被推迟到主线程任务完成后,因此最后执行。

功能实现完毕。

希望本文所述内容对大家的JavaScript程序设计有所帮助。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章