مخفی کردن هدر در هنگام اسکرول و برعکس
در این ویدیو شما می توانید با استفاده از این تکه کد ها هدر خود را جوری بکنید که موقع اسکرول مخفی بشه و وقتی دوباره به سمت بالا اسکرول کردی نمایش داده بشه
کد css
زبان: CSS
.rico-anim-header {
position: sticky;
top: 0;
transition: transform 0.3s ease-in-out;
z-index: 1000;
}
.header-hidden {
transform: translateY(-100%);
}
.header-visible {
transform: translateY(0);
}
کد js
زبان: JAVASCRIPT
<script>
class HeaderManager {
constructor() {
this.lastScrollY = 0;
this.scrollDirection = 'up';
this.scrollThreshold = 100;
this.hideThreshold = 700;
this.header = document.querySelector('.rico-anim-header');
this.init();
}
init() {
window.addEventListener('scroll', this.throttle(this.handleScroll.bind(this), 100));
}
handleScroll() {
const currentScrollY = window.scrollY;
if (currentScrollY > this.lastScrollY) {
this.scrollDirection = 'down';
} else {
this.scrollDirection = 'up';
}
// اگر از 700 پیکسل پایینتر رفتیم و به پایین اسکرول میکنیم
if (currentScrollY > this.hideThreshold && this.scrollDirection === 'down') {
this.hideHeader();
}
// اگر به بالا اسکرول میکنیم (با فاصله 100 پیکسل)
else if (this.scrollDirection === 'up' && (this.lastScrollY - currentScrollY) > this.scrollThreshold) {
this.showHeader();
}
this.lastScrollY = currentScrollY;
}
hideHeader() {
this.header.classList.add('header-hidden');
this.header.classList.remove('header-visible');
}
showHeader() {
this.header.classList.add('header-visible');
this.header.classList.remove('header-hidden');
}
throttle(func, limit) {
let inThrottle;
return function() {
const args = arguments;
const context = this;
if (!inThrottle) {
func.apply(context, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
}
}
}
document.addEventListener('DOMContentLoaded', function() {
new HeaderManager();
});
</script>