Sticky nav bar with jQuery jerky on window resize

末鹿安然 提交于 2019-12-11 14:56:46

问题


I'm working on a sticky nav-bar for the first time and I got everything working nicely until trying to make it responsive. When the window is resized, the jQuery for the nav bar causes the page to freeze for a bit feeling kind of jerky. Am I overdoing it with the resize checks?

jQuery(document).ready(function() {

    //on page load will get nav offset and wrap nav in a placeholder 
    //for smooth transition to fixed position
    var navOffset = jQuery('.nav').offset().top;
    jQuery('.nav').wrap('<div class="nav-placeholder"></div>');
    jQuery('.nav-placeholder').height(jQuery('.nav').outerHeight());

    //when window is resized will get new offset so nav 
    //goes sticky at right time
    jQuery(window).resize(function() {
    navOffset = jQuery('.nav').offset().top;
    jQuery('.nav').wrap('<div class="nav-placeholder"></div>');
    jQuery('.nav-placeholder').height(jQuery('.nav').outerHeight());
    });



    //added some extra wraps for styling purposes mainly padding
    jQuery('.nav').wrapInner('<div class="nav-inner"</div>');
    jQuery('.nav-inner').wrapInner('<div class="nav-inner-most"</div>');

    //when scrolling past offset will set nav to fixed 'sticky'
    //when scrolling back up will unset the fixed sticky nav
    jQuery(window).scroll(function() {
        var scrollPos = jQuery(window).scrollTop();

        if(scrollPos >= navOffset) {
            jQuery('.nav').addClass('fixed');
        }
        else {
            jQuery('.nav').removeClass('fixed');
        }
    });

});

Thanks


回答1:


You should limit the number of times the callbacks for events such as resize, scroll fire.

Common ways of achieving this is called throttle and debounce. Many javascript libraries such as underscore, lodash etc implement this.

In the case of jQuery, There is a jQuery plugin jquery-throttle-debounce

You can use it like

jQuery(window).resize($.debounce( 250, function() {
  navOffset = jQuery('.nav').offset().top;
  jQuery('.nav').wrap('<div class="nav-placeholder"></div>');
  jQuery('.nav-placeholder').height(jQuery('.nav').outerHeight());
}));


来源:https://stackoverflow.com/questions/35448051/sticky-nav-bar-with-jquery-jerky-on-window-resize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!