前言
本文為「JavaScript 30」教學影片的學習筆記。
目標
製作出類似手風琴效果的頁面。
筆記
首先是 CSS 的部分。
在 .panels 增加:
1 | display: flex; |
display: flex表示內部使用伸縮容器。
在 .panel 增加:
1 | flex: 1; |
flex: 1代表每一個伸縮容器有相同比例。flex-direction: column代表垂直顯示伸縮容器。
在 .panel > * 增加:
1 | flex: 1 0 auto; |
flex是flex-grow、flex-shrink、flex-basi的縮寫,預設値是0 1 auto。flex-grow是伸縮容器在主軸上占總容器的比例。flex-shrink是當容器空間不足時,伸縮容器在主軸上縮小的比例flex-basis是伸縮容器的初始尺寸。
增加 transform 如下:
1 | .panel > *:first-child { |
translateY表示 Y 軸的偏移量。
在 .panel.open 增加:
1 | flex: 5; |
再來是 JavaScript 的部分。
先取得所有 panel 元素。
1 | const panels = document.querySelectorAll('.panel'); |
設定一個 toggleOpen() 的方法。
1 | function toggleOpen() { |
toggle()方法會在指定元素被點擊時,在 2 個方法之間輪流切換。
設定一個 toggleActive() 的方法。
1 | function toggleActive(e) { |
- 因為不只一個
transitionend事件,所以需要使用e.propertyName綁定flex。
在 click 和 transitionend 事件出現時,分別觸發 toggleOpen() 和 toggleActive() 方法。
1 | panels.forEach(panel => panel.addEventListener('click', toggleOpen)); |