[英]How to offset top bar height dynamically when scrolling down
I am trying to offset an announcement bar when scrolling down, taking into consideration that the height of the bar is more important on smaller devices. 我试图在向下滚动时偏移公告栏,考虑到条形的高度在较小的设备上更重要。
Here's an example of what I want to achieve : https://8kflexwarm.com/ 这是我想要实现的一个例子: https : //8kflexwarm.com/
So I ended up with this piece of code, which is working, but I feel like it is not optimized, not clean code. 所以我最终得到了这段代码,这是有效的,但我觉得它没有优化,不是干净的代码。 I figure there must be a way to offset
$('.announcement-bar')
instead of doing it manually with window size. 我认为必须有一种方法来抵消
$('.announcement-bar')
而不是手动使用窗口大小。
Also, why is this code not working when I refresh the screen and I'm not on top of the page ? 另外,为什么当我刷新屏幕并且我不在页面顶部时,此代码无法正常工作?
Is there a way to improve this code without using a library ? 有没有办法在不使用库的情况下改进此代码?
if($(window).width() >= 686){ var a = $(".site-header").offset().top; function scrollListener(){ if($(document).scrollTop() > a) { $('.site-header').css({"margin-top":"-40px"}); $('.site-header').css({"transition":"0.4s"}); } else { $('.site-header').css({"margin-top":"0px"}); $('.site-header').css({"transition":"0.4s"}); } }; $(document).scroll(scrollListener); scrollListener(); } else if($(window).width() >= 370) { var a = $(".site-header").offset().top; function scrollListener(){ if($(document).scrollTop() > a) { $('.site-header').css({"margin-top":"-65px"}); $('.site-header').css({"transition":"0.4s"}); } else { $('.site-header').css({"margin-top":"0px"}); $('.site-header').css({"transition":"0.4s"}); } }; $(document).scroll(scrollListener); scrollListener(); } else { var a = $(".site-header").offset().top; function scrollListener(){ if($(document).scrollTop() > a) { $('.site-header').css({"margin-top":"-90px"}); $('.site-header').css({"transition":"0.4s"}); } else { $('.site-header').css({"margin-top":"0px"}); $('.site-header').css({"transition":"0.4s"}); } }; $(document).scroll(scrollListener); scrollListener(); };
Please provide a codePen, it makes it easier to help you with your question. 请提供codePen,它可以更轻松地帮助您解决问题。
I came up with this untested piece of javascript: 我想出了这个未经测试的javascript:
var myApp = (function(app) {
const $elements = {
siteHeader = null,
}
function setPosition() {
const scrollTop = $(document).scrollTop()
const offsetTop = $elements.siteHeader.offset().top
if(scrollTop > offsetTop){
$elements.siteHeader.css({'margin-top':`${$elements.siteHeader.height() * -1}px`})
} else {
$elements.siteHeader.css({'margin-top':'0px'})
}
}
function initialize() {
// Wait for all elements to be created
$(function() {
$elements.siteHeader = $('.site-header')
setPosition()
$(document).scroll(setPosition)
$(document).resize(setPosition)
})
}
initialize()
return app;
})(myApp || {})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.