简体   繁体   English

我如何改善此代码(固定的导航栏)?

[英]How i can improve this code (fixed navbar)?

I made this for i can fix navbar on site when i scroll page 我这样做是因为我可以在滚动页面时在网站上修复导航栏

How i can improve this code, can reduce it somehow? 我如何改善此代码,可以以某种方式减少它?

<nav class="main_menu">
// some code...
</nav>

var menu_offset_top_default = $('.main_menu').offset().top;
$(window).scroll(function() {
    var menu_offset_top = $('.main_menu').offset().top;
    if ($(window).scrollTop() >= menu_offset_top) {
        $('.main_menu').addClass('fixed-top');
    }
    if ($(window).scrollTop() < menu_offset_top_default || $(window).scrollTop() <= 0) {
        $('.main_menu').removeClass('fixed-top');
    }
});

You could use css position: sticky instead and get remove the jquery code 您可以使用css position: sticky代替,然后删除jquery代码

A stickily positioned element is an element whose computed position value is sticky. 粘性放置的元素是其计算的位置值为粘性的元素。 It's treated as relatively positioned until its containing block crosses a specified threshold (such as setting top to value other than auto) within its flow root (or the container it scrolls within), at which point it is treated as "stuck" until meeting the opposite edge of its containing block. 它被视为相对定位,直到其包含的块在其流根(或在其中滚动的容器)内超过指定的阈值(例如,将top设置为auto以外的值),在该点处将其视为“卡住”,直到达到其包含块的相对边缘。 Source . 来源

An example: 一个例子:

https://codepen.io/simevidas/pen/JbdJRZ https://codepen.io/simevidas/pen/JbdJRZ

You can just do it as follows with simple if-else block. 您可以使用简单的if-else块按如下方式进行操作。

$(window).scroll(function() {
    if ($(window).scrollTop() >= $('.main_menu').offset().top) {
        $('.main_menu').addClass('fixed-top');
    }
    else {
        $('.main_menu').removeClass('fixed-top');
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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