javascript 30day
目標:滑動的次導覽列
一、抓取頁面元素及建立事件
const triggers = document.querySelectorAll('.cool > li');
const background = document.querySelector('.dropdownBackground');
const nav = document.querySelector('.top');
function handleEnter() { this.classList.add('trigger-enter'); setTimeout(() => this.classList.add('trigger-enter-active'), 150) background.classList.add('open'); }
function handleLeave() { this.classList.remove('trigger-enter', 'trigger-enter-active'); background.classList.remove('open'); } triggers.forEach(trigger => trigger.addEventListener('mouseenter', handleEnter)) triggers.forEach(trigger => trigger.addEventListener('mouseleave', handleLeave))
|
事件僅有滑鼠滑入及滑出的效果,
二、新增動態效果
function handleEnter() { this.classList.add('trigger-enter'); setTimeout(() => this.classList.add('trigger-enter-active'), 150) background.classList.add('open');
const dropdown = this.querySelector('.dropdown'); const dropdownCoords = dropdown.getBoundingClientRect(); const navCoords = nav.getBoundingClientRect();
const coords = { height: dropdownCoords.height, width: dropdownCoords.width, top: dropdownCoords.top, left: dropdownCoords.left }
background.style.setProperty('width', `${coords.width}px`); background.style.setProperty('height', `${coords.height}px`); background.style.setProperty('transform', `translate(${coords.left}px,${coords.top}px)`) }
|
三、Debug 錯位與快速滑動
function handleEnter() { ... ... const coords = { height: dropdownCoords.height, width: dropdownCoords.width, top: dropdownCoords.top - navCoords.top, left: dropdownCoords.left - navCoords.left } ... ... }
|
假設主導覽列上方有新增元素,則下拉導覽列會錯位,為了避免錯位,因此必須扣除掉主導覽列的定位。
setTimeout(() => this.classList.contains('trigger-enter') && this.classList.add('trigger-enter-active'), 150);
|
為了避免快速滑動導覽列產生錯亂,因此在setTimeout
上增加判斷,
假設前者導覽有trigger-enter
的class,便增加trigger-enter-active
,
假設沒有,則會一直顯示白色導覽列的部分,內容不會被顯示出來。