Geophysics_day1 / script.js
cwadayi's picture
Update script.js
f00581b verified
raw
history blame
3.02 kB
document.addEventListener('DOMContentLoaded', () => {
// --- 區塊淡入動畫 ---
const sections = document.querySelectorAll('section');
const sectionObserver = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('visible');
}
});
}, {
threshold: 0.05 // *** 降低觸發門檻,修復手機版底部區塊無法顯示問題 ***
});
sections.forEach(section => {
sectionObserver.observe(section);
});
// --- 回到頂部按鈕 ---
const backToTopButton = document.querySelector('.back-to-top');
window.addEventListener('scroll', () => {
if (window.pageYOffset > 300) {
backToTopButton.classList.add('visible');
} else {
backToTopButton.classList.remove('visible');
}
});
// --- 導覽列高亮 ---
const navLinks = document.querySelectorAll('.nav-link');
const navObserver = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const id = entry.target.getAttribute('id');
navLinks.forEach(link => {
link.classList.remove('active');
if (link.getAttribute('href') === `#${id}`) {
link.classList.add('active');
}
});
}
});
}, {
rootMargin: '-50% 0px -50% 0px'
});
document.querySelectorAll('section[id]').forEach(section => {
navObserver.observe(section);
});
// --- ★★★★★ 修正並簡化後的燈箱功能 ★★★★★ ---
document.body.addEventListener('click', function(event) {
// 檢查點擊的是否是帶有 .lightbox-trigger 的 <a> 標籤
const trigger = event.target.closest('.lightbox-trigger');
if (trigger) {
event.preventDefault(); // 阻止連結的默認跳轉行為
const imageUrl = trigger.getAttribute('href');
// 如果頁面上已經有燈箱,就不要再創建
if (document.querySelector('.lightbox')) {
return;
}
// 創建燈箱元素
const lightbox = document.createElement('div');
lightbox.className = 'lightbox';
lightbox.innerHTML = `<img src="${imageUrl}" alt="放大圖片">`;
// 將燈箱加入到 body
document.body.appendChild(lightbox);
// 監聽點擊燈箱本身以關閉
lightbox.addEventListener('click', () => {
lightbox.classList.add('closing');
setTimeout(() => {
if (document.body.contains(lightbox)) {
document.body.removeChild(lightbox);
}
}, 300); // 等待淡出動畫結束
});
}
});
});