滚动时粘滞子导航,调整大小时会中断 [英] Sticky subnav when scrolling past, breaks on resize
问题描述
我有一个固定在顶部的主标题,还有一个固定在窗口底部的subnav(在实际站点上是用于页面内的锚链接).然后,我得到一个英雄图像,它是窗口的高度减去标题的高度,再减去子导航的高度.当用户滚动到底部的子导航时,紧接着在主导航之后停留在顶部.目前,这一切都很好.
I have a main header that is fixed to the top and I have a subnav (which on the real site is for anchor links within the page) which is fixed to the bottom of the window. I then have a hero image which is the height of the window minus the height of the header and minus the height of the subnav. When a user scrolls past the subnav at the bottom, it then sticks to the top just after the main navigation. This all works pretty well at the moment.
以下是其在开发中的网站上的工作原理的摘录版本: https://jsfiddle.net/owgvjxdj.
Here's an extracted version of how it works on the site that's under development: https://jsfiddle.net/owgvjxdj.
但是,一个错误是,当调整窗口大小时,不会重新计算子导航的位置,因此最终定位得太高或太低.
However, the one bug is that when the window is resized, the subnav's position isn't recalculated and so ends up positioned either too high or too low.
我可以通过绑定其他窗口调整大小事件来重构子导航的位置:
I can refactor for the subnav's position by binding an additional window resize event:
// Refactor subnav measurements on window resize
$( window ).resize(function() {
var windowH = $(window).height();
var stickToBot = windowH - $('#subnav').outerHeight(true);
var scrollVal = $(this).scrollTop();
if ( scrollVal > stickToBot - $('.navbar').outerHeight(true) ) {
$('#subnav').css({'position':'fixed','top' :'80px'});
} else {
$('#subnav').css({'position':'absolute','top': stickToBot +'px'});
}
});
这适用于初始位置,但是在滚动然后调整窗口大小之后,定位不正确: https: //jsfiddle.net/owgvjxdj/1/
This works for the initial position, but after scrolling and then resizing the window, the positioning is incorrect: https://jsfiddle.net/owgvjxdj/1/
我知道我在这里遗漏了一些非常明显的东西,但这是什么?!
I know I'm missing something very obvious here but what is it?!
推荐答案
,您需要再次更新windowH
,最后是sticktoBot
,因此使变量成为全局变量,并在调整窗口大小时更新其值,这是小提琴- http://jsfiddle.net/owgvjxdj/4/
you need to update the windowH
again and finally sticktoBot
, so make the variables global and update their value when window resizes, here is the fiddle - http://jsfiddle.net/owgvjxdj/4/
这篇关于滚动时粘滞子导航,调整大小时会中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!