1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <meta http-equiv="X-UA-Compatible" content="IE=edge"> 7 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 8 <title>Document</title> 9 <style> 10 * { 11 margin: 0; 12 padding: 0; 13 } 14 15 span { 16 display: inline-block; 17 width: 200px; 18 height: 20px; 19 } 20 21 .box { 22 width: 200px; 23 background-color: gray; 24 } 25 26 li { 27 list-style: none; 28 width: 200px; 29 height: 20px; 30 } 31 32 #box1, 33 #box2, 34 #box3, 35 #box4, 36 #box5 { 37 overflow: hidden; 38 } 39 40 .he { 41 height: 20px; 42 } 43 </style> 44 <script src="js/tools.js"></script> 45 <script> 46 window.onload = function () { 47 let spanMenu = document.getElementsByClassName("spanMenu") 48 let current = 0 49 for (let i = 0; i < spanMenu.length; i++) { 50 spanMenu[i].onclick = function () { 51 52 let pardiv = this.parentElement 53 // 定义一个begin来记录父元素变化之前的高度 54 let begin = pardiv.offsetHeight 55 // console.log(begin) 56 toggleClass(pardiv, "he") 57 // 定义一个end来记录父元素变化之后的高度 58 let end = pardiv.offsetHeight 59 // console.log(end ) 60 // 将父元素变为开始的高度,增加动画 61 pardiv.style.height = begin + "px" 62 move(pardiv, "height", end, 10, function () { 63 pardiv.style.height = "" 64 }) 65 if (current != i && !hasClass(spanMenu[current].parentElement, "he")) { 66 let pardiv = spanMenu[current].parentElement 67 let begin = pardiv.offsetHeight 68 toggleClass(pardiv, "he") 69 let end = pardiv.offsetHeight 70 pardiv.style.height = begin + "px" 71 move(pardiv, "height", end, 10, function () { 72 pardiv.style.height = "" 73 }) 74 75 // 两部分加动画的代码大致相同,也能封装 76 } 77 current = i 78 } 79 } 80 } 81 82 </script> 83 84 </head> 85 86 <body> 87 <div id="box" class="box"> 88 <div id="box1"> 89 <span class="spanMenu">标题1</span> 90 <ul> 91 <li>1-1</li> 92 <li>1-2</li> 93 <li>1-3</li> 94 </ul> 95 </div> 96 <div id="box2" class="he"> 97 <span class="spanMenu">标题2</span> 98 <ul> 99 <li>1-1</li> 100 <li>1-2</li> 101 <li>1-3</li> 102 </ul> 103 </div> 104 <div id="box3" class="he"> 105 <span class="spanMenu">标题3</span> 106 <ul> 107 <li>1-1</li> 108 <li>1-2</li> 109 <li>1-3</li> 110 </ul> 111 </div> 112 <div id="box4" class="he"> 113 <span class="spanMenu">标题4</span> 114 <ul> 115 <li>1-1</li> 116 <li>1-2</li> 117 <li>1-3</li> 118 </ul> 119 </div> 120 <div id="box5" class="he"> 121 <span class="spanMenu">标题5</span> 122 <ul> 123 <li>1-1</li> 124 <li>1-2</li> 125 <li>1-3</li> 126 </ul> 127 </div> 128 129 </div> 130 </body> 131 132 </html>
原文:https://www.cnblogs.com/lay529/p/15100937.html