[英]Position fixed when scroll down hopping when the screen is not very big
I'm trying to make my header fixed when the user scroll down. 当用户向下滚动时,我正在尝试修复标题。 The problem is if the content on the page is not big enough the screen hopping.
问题是页面上的内容是否不够大,导致屏幕跳动。 Also when I scroll to the top again it change from fixed to normal very hard.
同样,当我再次滚动到顶部时,它很难从固定变为正常。 Can someone help me with this?
有人可以帮我弄这个吗?
window.addEventListener('scroll', function() {
if($(window).scrollTop() == 0) {
$('.sticky-wrapper').removeClass('stickynow');
} else {
$('.sticky-wrapper').addClass('stickynow');
}
});
I don't really understand what 'screen hopping' means, but i guess what happens is that when your header becomes position:fixed
, it doesn't occupy space anymore so the content
moves up to fill that space an thus, 'hopping'. 我不太了解“屏幕跳变”的含义,但我想会发生什么情况,就是当您的标题变为
position:fixed
,它不再占用空间,因此content
会向上移动以填充该空间,从而“跳变” 。
You should add margin-top to your content ( or whichever element is right after the header in HTML structure ) equal to the header's height. 您应该在内容中添加margin-top(或HTML结构中标头之后的任何元素),使其等于标头的高度。
See below 见下文
window.addEventListener('scroll', function() { let header = $('.sticky-wrapper') if ($(window).scrollTop() == 0) { $(header).removeClass('stickynow'); $('section').css({ 'margin-top': 0 }) } else { $(header).addClass('stickynow'); $('section').css({ 'margin-top': $(header).height() }) } });
header { width: 100%; height: 100px; background: red; } .stickynow { position: fixed; background: blue; top: 0; left: 0; } section { height: 1000px; width: 100%; background: green; } body, html { margin: 0; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <header class="sticky-wrapper"></header> <section>Not 'Hopping'</section>
OPTION B. Without javascript/jQuery 选项B.不使用javascript / jQuery
If you don't need to add a class or something else that involves javascript/jQuery, you can have the same result as above, but only with css 如果您不需要添加类或涉及javascript / jQuery的其他内容,则可以得到与上述相同的结果,但只能使用CSS
header { position: fixed; background: blue; top: 0; left: 0; height:100px; width:100%; } section { height: 1000px; width: 100%; background: green; margin-top:100px; /*add this*/ } body, html { margin: 0; }
<header class="sticky-wrapper"></header> <section>Not 'Hopping'</section>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.