學習筆記-JS30-Day5-Flex Panels Image Gallery

vincentxu
3 min readMar 21, 2023

--

今日重點:

透過點擊圖片可以打開照片,並帶有動畫移動文字。

程式碼:github
線上看:Demo

學習筆記:

關鍵

1. 設定CSS

2. 取得元素的控制權

3. 監聽按鈕

4. 控制按鈕來改變CSS

設定CSS變數

//最外圈的css要橫排
.panels {
min-height: 100vh;
overflow: hidden;
display:flex;
}

//每一格的css要置中,等分
.panel {
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
//設定文字的排列,等分
.panel > * {
margin: 0;
width: 100%;
transition: transform 0.5s;
flex: 1 0 auto;
display: flex;
justify-content: center;
align-items: center;
}
//設定css動畫
.panel > *:first-child { transform: translateY(-100%); }
.panel.open-active > *:first-child { transform: translateY(0%); }
.panel > *:last-child { transform: translateY(100%); }
.panel.open-active > *:last-child { transform: translateY(0); }

取得元素的控制權

const panels = document.querySelectorAll('.panel');

監聽元素

panels.forEach(panel => panel.addEventListener('click',toggleOpen));
panels.forEach(panel => panel.addEventListener('transitionend',toggleActive));

控制元素來改變CSS

function toggleOpen(){
this.classList.toggle('open');
}
function toggleActive(e){
if(e.propertyName.includes('flex')){
this.classList.toggle('open-active');
}
}

每次看到不同思維,都覺得很有收穫,補充在下方

//一樣都是選擇判斷,不同做法

function toggleActive(e){
if(e.propertyName.includes('flex')) {
this.classList.toggle('open-active');
}
}

function toggleActive(e){
if(e.propertyName.indexOf('flex')!== -1) {
this.classList.toggle('open-active');
}
}

--

--

vincentxu
vincentxu

Written by vincentxu

熱愛學習、戶外運動,關心教育,曾任公部門主計,教育工作者/軟體工程師_嘗試將科技與使用者經驗設計導入教育_共同創辦一個線上教育平台,推廣自主學習與民主教育https://www.daoedu.tw/

No responses yet