[英]Scrolling Nav Sticks to Top
My problem is along the lines of these previous issues on StackOverflow but with a slight difference. 我的问题与StackOverflow上的这些先前问题类似,但有细微差别。
Previous issues: Stopping fixed position scrolling at a certain point? 先前的问题: 在某个位置停止固定位置滚动? Sticky subnav when scrolling past, breaks on resize 滚动时粘滞子导航,调整大小时会中断
I have a sub nav that starts at a certain position in the page. 我有一个从页面中某个位置开始的子导航。 When the page is scrolled the sub nav needs to stop 127px from the top. 滚动页面时,子导航需要从顶部停止127px。 Most of the solutions I have found need you to specify the 'y' position of the sub nav first. 我发现的大多数解决方案都需要您先指定子导航的“ y”位置。 The problem with this is that my sub nav will be starting from different positions on different pages. 问题是我的子导航将从不同页面上的不同位置开始。
This is the JS code i'm currently using. 这是我当前正在使用的JS代码。 This works fine for one page but not all. 此功能仅适用于一页,但并非全部。 Plus on mobile the values would be different again. 再加上在移动设备上的值将再次不同。
var num = 660; //number of pixels before modifying styles
$(window).bind('scroll', function () {
if ($(window).scrollTop() > num) {
$('.menu').addClass('fixed');
} else {
$('.menu').removeClass('fixed');
}
});
I'm looking for a solution that stops the sub nav 127px from the top no matter where on the page it started from. 我正在寻找一种解决方案,无论它从页面的哪个位置开始,都从顶部停止子导航127px。
You can use position: sticky
and set the top
of the sub-nav to 127px
. 您可以使用position: sticky
并将子导航的top
设置为127px
。
See example below: 请参见下面的示例:
body { margin: 0; } .main-nav { width: 100%; height: 100px; background-color: lime; position: sticky; top: 0; } .sub-nav { position: sticky; width: 100%; height: 50px; background-color: red; top: 100px; } .contents { width: 100%; height: 100vh; background-color: black; color: white; } .contents p { margin: 0; }
<nav class="main-nav">Main-nav</nav> <div class="contents"> <p>Contents</p> </div> <nav class="sub-nav">Sub-nav</nav> <div class="contents"> <p>More contents</p> </div>
Please see browser support for sticky here
请sticky here
查看浏览器支持
You should change your code to the below, should work fine: 您应该将代码更改为以下内容,并且可以正常运行:
$(window).bind('scroll', function () {
if ($(window).scrollTop() > $(".menu").offset().top) {
$('.menu').addClass('fixed');
} else {
$('.menu').removeClass('fixed');
}
});
Maybe you can try this: 也许您可以尝试以下方法:
.menu
) 查找导航div( .menu
) .menu
(vanilla JS would be menuVar.getBoundingClientRect().top
, not sure how jQuery does this). 找到.menu
的最高值(香草JS是menuVar.getBoundingClientRect().top
,不确定jQuery如何做到这一点)。 menu -127px
-> addClass('fixed')
. 当用户滚动并到达menu -127px
的最高值menu -127px
> addClass('fixed')
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.