想要用 Elemetor 製作固定在上方的Header,同時又能在滑鼠向下滾動時縮小,
另外在縮放不同的瀏覽器螢幕大小時,也要能維持上述功能。
我們可以先參考 Elementor官方的來進行Elementor編輯器中的設定 https://elementor.com/blog/shrinking-sticky-header/
不過,該指南對2024最新版本的Elementor提到的Container概念做法,似乎沒甚麼作用。
修正js碼如下(放在CodeWP外掛):
document.addEventListener('DOMContentLoaded', function() { var header = document.querySelector('.sticky-header'); var shrinkOn = 0; function updateShrinkOn() { var viewportWidth = window.innerWidth; if (viewportWidth >= 1025) { shrinkOn = 145; } else if (viewportWidth >= 768) { shrinkOn = 120; } else { shrinkOn = 90; } } updateShrinkOn(); window.addEventListener('scroll', function() { if (window.scrollY > shrinkOn) { header.classList.add('shrink'); } else { header.classList.remove('shrink'); } }); window.addEventListener('resize', function() { updateShrinkOn(); }); });
修正CSS碼如下(放在Elementor編輯器Header頂端的齒輪設定內>進階>CSS):
/* Basic styles for header and logo */ selector .sticky-header { position: fixed; /* 确保Header固定在顶部 */ top: 0; width: 100%; transition: height 0.5s ease; z-index: 9999; /* 确保Header在最上层 */ } selector .sticky-header .logo { transition: transform 0.5s ease; transform-origin: left center; /* Set the scaling point to the left */ } /* Starting heights for different devices */ @media (min-width: 1025px) { selector .sticky-header { height: 145px; } } @media (min-width: 768px) and (max-width: 1024px) { selector .sticky-header { height: 120px; } } @media (max-width: 767px) { selector .sticky-header { height: 90px; } } /* Reduced heights when scrolling */ @media (min-width: 1025px) { selector .sticky-header.shrink { height: 105px; /* 75% of 125px */ } } @media (min-width: 768px) and (max-width: 1024px) { selector .sticky-header.shrink { height: 85px; /* 75% of 120px */ } } @media (max-width: 767px) { selector .sticky-header.shrink { height: 65px; /* 75% of 90px */ } } /* Reduced logo size when scrolling */ selector .sticky-header.shrink .logo { transform: scale(0.7); }
大功告成