繁体   English   中英

屏幕不是很大时向下滚动时位置固定

[英]Position fixed when scroll down hopping when the screen is not very big

当用户向下滚动时,我正在尝试修复标题。 问题是页面上的内容是否不够大,导致屏幕跳动。 同样,当我再次滚动到顶部时,它很难从固定变为正常。 有人可以帮我弄这个吗?

window.addEventListener('scroll', function() {
if($(window).scrollTop() == 0) {
    $('.sticky-wrapper').removeClass('stickynow');
} else {
    $('.sticky-wrapper').addClass('stickynow');
}
});

我不太了解“屏幕跳变”的含义,但我想会发生什么情况,就是当您的标题变为position:fixed ,它不再占用空间,因此content会向上移动以填充该空间,从而“跳变” 。

您应该在内容中添加margin-top(或HTML结构中标头之后的任何元素),使其等于标头的高度。

见下文

 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> 

选项B.不使用javascript / jQuery

如果您不需要添加类或涉及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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM