首页 > 代码库 > 简单但很实用的js手风琴效果

简单但很实用的js手风琴效果

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>
body,ul,li,.sfq,h3{
    margin: 0;
    padding: 0;
    list-style: none;
}
  h3{
      height: 30px;
      width: 200px;
      background-color: #00cdc5;
      text-align: center;
      line-height: 30px;
      color: #fff;

  }
        li{
            height: 30px;
            width: 200px;
            background-color: rgba(158, 123, 255, 0.26);
            color: #fff;

        }
        ul{
            overflow: hidden;
        }
    </style>
</head>
<body>
<div id="hello">
   <h3 >我在第一楼</h3>
    <ul>
         <li>good luck </li>
        <li>hello javascript</li>
        <li>hello programmer</li>
        
    </ul>
    <h3>我在第二楼</h3>
    <ul>
       <li>good luck </li>
        <li>hello javascript</li>
        <li>hello programmer</li>
    </ul>
    <h3 >我在第三楼</h3>
    <ul>
         <li>good luck </li>
        <li>hello javascript</li>
        <li>hello programmer</li>
    </ul>
</div>
<script type="text/javascript">
    function $(id) {
        return document.getElementById(id);
    }
var temph3 = $(‘hello‘).getElementsByTagName(‘h3‘); //得到h3的节点对象
    for(var i=0;i<temph3.length;i++)
    { temph3[i].onclick=function(){
            var tempnext= this.nextElementSibling;//h3下一个兄弟元素节点ul,避免指向空节点;
             if(tempnext.style.display!=‘none‘){ //如果ul没有被关闭则执行代码
                 var offsethight=tempnext.offsetHeight; //设置当前ul的可见高度
                 var setintervalid = setInterval(
                         function(){
                             offsethight=tempnext.offsetHeight;
                             tempnext.style.height=offsethight-10+‘px‘;//★逐渐关闭的时候,ul一定要overflow: hidden;
                             if(offsethight<10){  //当高度小于10时改变display的值为none,并关闭时间间隔;
                                 tempnext.style.display=‘none‘;
                                 clearInterval(setintervalid);

                             }
                         },50
                 )
             }else //如果ul处于关闭状态则执行代码
             {
                 tempnext.style.display=‘block‘;//首先设置display为可见状态
                 var offsethight=tempnext.offsetHeight;        
                 var setintvalid=setInterval(function(){
                      offsethight=tempnext.offsetHeight;
                     tempnext.style.height=offsethight+10+‘px‘;//高度加10
                     if(offsethight>=90){
                         tempnext.style.height=offsethight+‘px‘;// ★让最后停止的ul高度等于可见的高度,避免了出现空白的现象;
                         clearInterval(setintvalid);
                     }

                 },50)

             }
        }
    }

</script>
</body>
</html>