在窗口调整大小时带有jQuery生涩的粘性导航栏

在窗口调整大小时带有jQuery生涩的粘性导航栏

本文介绍了在窗口调整大小时带有jQuery生涩的粘性导航栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是第一次在粘性导航栏上工作,在使它响应之前,一切工作都很好.调整窗口大小时,导航栏的jQuery使页面冻结,感觉有点生涩.我是否会通过调整大小检查来解决这个问题?

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');
        }
    });

});

谢谢

推荐答案

您应限制事件resizescroll触发事件的回调次数.

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

实现此目的的常用方法称为油门和反跳".许多JavaScript库(例如下划线,lodash等)都可以实现此功能.

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

对于jQuery,有一个jQuery插件 jquery-throttle-debounce

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

您可以像使用它

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());
}));

这篇关于在窗口调整大小时带有jQuery生涩的粘性导航栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 03:01