首页 > 展开收缩,用事件代理来写的话怎样写,总是有问题,求助

展开收缩,用事件代理来写的话怎样写,总是有问题,求助

展开收缩,用事件代理来写的话怎样写,总是有问题

展开收缩不是那么的顺畅

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
#ul1 {width: 100px; padding: 0;}
#ul1 li {width: 100px; list-style: none;}
#ul1 li h2 {margin: 0; padding: 0; height: 20px; background: #ccc; font-size: 12px; font-weight: normal; text-align: center; line-height: 20px; border: 1px solid #333;}
#ul1 li div {height: 100px; background: red; display: none;}

</style>

</head>

<body>
  <ul id="ul1">
          <li>
            <h2> 1111 </h2>
            <div id="a1"></div>
    </li>
          <li>
            <h2> 2222 </h2>
            <div id="a2"></div>
    </li>
          <li>
            <h2> 3333 </h2>
            <div id="a3"></div>
    </li>
          <li>
            <h2> 4444 </h2>
            <div id="a4"></div>
    </li>
  </ul>

  <script>
window.onload=function(){
        var ul=document.getElementById('ul1');
        var li=ul.getElementsByTagName('h2');
        var div=ul.getElementsByTagName('div');

        ul.addEventListener('click', function(e){
                
                if(e.target.parentNode.tagName = 'LI'){

                        for(var i=0; i<div.length; i++){
                                div[i].style.display = 'none'
                        }
                        console.log(e.target.parentNode,e.target.parentNode.getElementsByTagName('div')[0])
                        var elem = e.target.parentNode.getElementsByTagName('div')[0];
                        if(elem.show==1){
                                elem.style.display = 'none'
                                elem.show=0
                        }else{
                                elem.style.display = 'block'
                                elem.show=1;
                        }
                }
        })
};
</script>
</body>
</html>

试下jQuery的slideDown() slideUp() 或者 toggle()

【热门文章】
【热门文章】