简体   繁体   English

如何创建一个 header 和 JQuery,它在向上滚动时固定在顶部但在向下滚动时隐藏?

[英]How do I create a header with JQuery that is fixed on top on scroll up but hides on scroll down?

I am currently working on a site product where I have to create a site-header that is always fixed on top of the viewport but when I scroll down it hides, and again when I scroll up, it becomes visible again.我目前正在开发一个网站产品,我必须创建一个始终固定在视口顶部的网站标题,但是当我向下滚动时它会隐藏,而当我向上滚动时它又会再次可见。 Actually, I made it happen somehow but I think the JQuery I used can be simpler and currently have some unnecessary variations in it.实际上,我以某种方式实现了它,但我认为我使用的 JQuery 可以更简单,并且目前有一些不必要的变化。 I used the JQuery from a reference available on inte.net.我使用了来自 inte.net 上可用参考的 JQuery。

Here is my code.这是我的代码。

HTML HTML

    <header class="site-header">
        <div class="inner">
        </div>
    </header>

CSS CSS

    .site-header {
    position: fixed;
    top: 0;
    z-index: 1;
    width: 100%;
    height: 60px;
    background: #fff;
    transition: transform .25s;}

    .hidden {transform:translateY(-100%)}

JQuery JQuery

    jQuery( function( $ ) {
        var didScroll;
        var lastScrollTop = 0;
        var delta = 5;
        var navbarHeight = $('.site-header').outerHeight();

        $(window).scroll(function(event){
            didScroll = true;
        });

    setInterval(function() {
        if (didScroll) {
        hasScrolled();
        didScroll = false;
        }
    }, 250);

    function hasScrolled() {
    var st = $(this).scrollTop();

    // Make scroll more than delta
    if(Math.abs(lastScrollTop - st) <= delta)
        return;

    // If scrolled down and past the site-header, add class .hidden.
    if (st > lastScrollTop && st > navbarHeight){
        // Scroll Down
        $('.site-header').addClass('hidden');
    } else {
        // Scroll Up
        if(st + $(window).height() < $(document).height()) {
            $('.site-header').removeClass('hidden');
        }
    }

    lastScrollTop = st;
    }
    } );

Now, all these things together are functional and I have a header that is fixed, but when I scroll down, it disappears and when I scroll back up, it becomes visible again- as I wanted.现在,所有这些东西都起作用了,我有一个固定的 header,但是当我向下滚动时,它消失了,当我向上滚动时,它再次变得可见——正如我想要的那样。 But, since I am not much familiar with JQuery at all, I am not sure if this JQuery can be more simpler.但是,由于我对 JQuery 一点都不熟悉,我不确定这个 JQuery 是否可以更简单一些。 Because, I think it would be great if I can achieve the same results with a smaller and simpler JQuery.因为,我认为如果我能用更小更简单的 JQuery 实现相同的结果,那就太好了。

I made this work but I believe a smaller and simpler JQuery can make this same function work too.我完成了这项工作,但我相信更小更简单的 JQuery 也可以使同样的 function 工作。

This solution shows a fixed header that fades out and in on scroll.此解决方案显示固定的 header,它在滚动时淡出和淡入。 A conf.hideFactor threshold determines at what scroll pos the header fades out, 0.5 is half the header height. conf.hideFactor阈值决定 header 在哪个滚动位置淡出, 0.5是 header 高度的一半。 The trick is to hide/show only when needed, done with a .is(':visible') check诀窍是仅在需要时隐藏/显示,通过.is(':visible')检查完成

 const conf = { hideFactor: 0.5 // factor of site-header height to hide }; $('document').ready(function() { const $headerElem = $('.site-header'); let navbarHeight = $headerElem.outerHeight(); $(document).scroll(function() { let scrollPos = Math.round($(document).scrollTop()); let headerIsVisible = $headerElem.is(':visible'); if(scrollPos > navbarHeight * conf.hideFactor) { if(headerIsVisible) { console.log('Hide at ' + scrollPos); $headerElem.hide('slow'); } } else if(.headerIsVisible) { console;log('Show at ' + scrollPos). $headerElem;show('slow'); } }); });
 .site-header { position: fixed; z-index: 1; width: 500px; height: 60px; background-color: #eaeaea; padding: 5px 10px; }.main-content { width: 500px; background-color: #fafafa; padding: 65px 10px 5px 10px; }.as-console-wrapper { max-height: 20px;important; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="page"> <header class="site-header"> <div class="inner"> This header is fixed and fades away on scroll </div> </header> <div class="main-content"> <h1>Lorem ipsum dolor sit amet</h1> <p>Consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> <p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. </p> <p>Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. </p> <p>Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?</p> </div> </div>

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

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