简体   繁体   English

如何制作粘性标头?

[英]How to make a sticky header?

I'm trying to make a sticky navbar so that when I scroll down I want my logo, my search bar, sign in button and my navbar scroll down as well. 我正在尝试制作一个粘性导航栏,以便当我向下滚动时,我希望我的徽标,搜索栏,登录按钮以及导航栏也向下滚动。

The problem is that when I'm scrolling down, my logo and nav bar go behind my slideshow; 问题是,当我向下滚动时,徽标和导航栏会进入幻灯片显示的后面。 they do not show and they're also transparent. 它们不显示,并且也是透明的。 I'm working on it for 2 days now but couldn't figure it out. 我正在处理2天,但无法解决。

 div#shopify-section-header { position: fixed; background-color: black; } 
 <div id="shopify-section-header" class="shopify-section header-section"> <header class="site-header" role="banner" data-section-id="header" data-section-type="header-section"> <div class="wrapper"> <div class="grid--full"> <div class="grid-item large--one-half"> <h1 class="header-logo" itemscope="" itemtype="http://schema.org/Organization"> <a href="/" itemprop="url"> <img src="//cdn.shopify.com/s/files/_tagline_bpng?v=1512661427" srcset="//tagline_black_whitebkg_250x.png?v=1512661427 1x, //cdn.shopify.com/s/files/1/2045/6673/files/Ctagline_black_whitebkg_250x@2x.png?v=1512661427 2x" alt="test" itemprop="logo"> </a> </h1> <div class="clearfix"></div> <a class="contact-header-logo" href="/pages/contact-us">Contact Us</a> </div> <div class="grid-item large--one-half text-center large--text-right"> <div class="site-header--text-links medium-down--hide"> <div id="ly-languages-switcher"> <a href="#" id="ly40221" class="ly-languages-switcher-link current_lang">English</a> <span>/</span> <a href="#" id="ly40222" class="ly-languages-switcher-link">Français</a> </div> <div class="currencyRobo medium-down--hide"> <div class="currencyRoboSelect"> <select class="currencyRoboSelectBox" name="currencyRoboSelect"> <option value="CAD">CAD</option> <option value="CHF">CHF</option> <option value="EUR">EUR</option> <option value="GBP">GBP</option> <option value="USD">USD</option> </select> </div> </div> <span class="site-header--meta-links medium-down--hide"> <a href="/account/login" id="customer_login_link">Sign in</a> <span class="site-header--spacer">or</span> <a href="/account/register" id="customer_register_link">Create an Account</a> </span> </div> <br class="medium-down--hide"> <form action="/pages/search-results" method="get" class="search-bar" role="search"> <input type="hidden" name="type" value="product"> <input type="search" name="q" value="" placeholder="Search all products..." aria-label="Search all products..." class="stop-mega-menu-reinit" autocomplete="OfF" id="_ispbxii_0" autocorrect="off" autocapitalize="off"> <button type="submit" class="search-bar--submit icon-fallback-text"> <span class="icon icon-search" aria-hidden="true"></span> <span class="fallback-text">Search</span> </button> </form> <a href="/cart" class="header-cart-btn"> <span class="icon icon-cart"></span> Cart <span class="cart-count cart-badge--desktop hidden-count">0</span> </a> </div> </div> </div> </header> <nav class="nav-bar sticky-header" role="navigation"> <div class="wrapper"> <form action="/pages/search-results" method="get" class="search-bar" role="search"> <input type="hidden" name="type" value="product"> <input type="search" name="q" value="" placeholder="Search all products..." aria-label="Search all products..." class="stop-mega-menu-reinit" autocomplete="OfF" id="_ispbxii_1" autocorrect="off" autocapitalize="off"> <button type="submit" class="search-bar--submit icon-fallback-text"> <span class="icon icon-search" aria-hidden="true"></span> <span class="fallback-text">Search</span> </button> </form> </div> </nav> </div> 

Check this Fiddle. 检查这个小提琴。 There are a couple of issues in your HTML, like your wrapping DIV is not closed. HTML中有几个问题,例如包装DIV未关闭。 First try to fix the HTML, then add CSS to position your sticky DIVs separately. 首先尝试修复HTML,然后添加CSS分别放置粘性DIV。

HTML: HTML:

<div id="shopify-section-header" class="shopify-section header-section">

  <header class="site-header" role="banner" data-section-id="header" data-section-type="header-section">
    <div class="wrapper">
      <h1 class="header-logo" itemscope="" itemtype="http://schema.org/Organization">
            <a href="/" itemprop="url">
              <img src="//cdn.shopify.com/s/files/_tagline_black_whitebkg_250x.png?v=1512661427" srcset="//cdn.shopify.com/s/files/1/2045/6673/files/Camomile_logo_tagline_black_whitebkg_250x.png?v=1512661427 1x, //cdn.shopify.com/s/files/1/2045/6673/files/Camomile_logo_tagline_black_whitebkg_250x@2x.png?v=1512661427 2x"
                alt="Camomile Beauty Always Cruelty free, Organic, Vegan and Safe skincare" itemprop="logo">
            </a>
          </h1>
    </div>
  </header>

  <nav class="nav-bar sticky-header" role="navigation">
    <div class="wrapper">
      This is also sticky
    </div>
  </nav>

  <div class="content">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Urna nec tincidunt praesent semper feugiat nibh sed. A lacus vestibulum sed arcu non odio euismod lacinia. Tellus mauris a diam maecenas. At tempor commodo ullamcorper a lacus vestibulum sed. Feugiat nibh sed pulvinar proin gravida hendrerit lectus a. Leo a diam sollicitudin tempor id eu nisl. Viverra mauris in aliquam sem fringilla ut morbi tincidunt. At ultrices mi tempus imperdiet nulla malesuada. Nullam eget felis eget nunc. Dictumst vestibulum rhoncus est pellentesque elit ullamcorper dignissim cras tincidunt.

Massa tincidunt dui ut ornare lectus sit. Posuere urna nec tincidunt praesent semper. Nec tincidunt praesent semper feugiat nibh sed pulvinar proin gravida. Sapien et ligula ullamcorper malesuada proin libero. Quam adipiscing vitae proin sagittis nisl rhoncus mattis rhoncus. Nunc id cursus metus aliquam eleifend mi in nulla. Viverra nibh cras pulvinar mattis nunc sed blandit libero. Tincidunt dui ut ornare lectus sit amet. Sagittis purus sit amet volutpat consequat mauris. Libero justo laoreet sit amet cursus sit amet dictum sit. Viverra adipiscing at in tellus. Lobortis scelerisque fermentum dui faucibus. Cum sociis natoque penatibus et magnis dis. Quisque sagittis purus sit amet volutpat. Aliquam sem et tortor consequat id. Pellentesque diam volutpat commodo sed egestas. Id semper risus in hendrerit gravida. Tincidunt dui ut ornare lectus sit. Non quam lacus suspendisse faucibus interdum posuere. Faucibus scelerisque eleifend donec pretium vulputate sapien nec sagittis.

Et netus et malesuada fames ac turpis egestas. Amet porttitor eget dolor morbi non. Id neque aliquam vestibulum morbi blandit. Et malesuada fames ac turpis. Non curabitur gravida arcu ac tortor dignissim. Id consectetur purus ut faucibus pulvinar elementum integer enim neque. Sit amet consectetur adipiscing elit ut aliquam purus. Leo vel orci porta non. Aliquet nibh praesent tristique magna sit amet purus gravida. Laoreet non curabitur gravida arcu ac tortor. Aenean vel elit scelerisque mauris. Mauris augue neque gravida in fermentum et sollicitudin ac. Non sodales neque sodales ut etiam sit amet nisl. Vel facilisis volutpat est velit egestas dui id. In metus vulputate eu scelerisque felis imperdiet proin fermentum. Non tellus orci ac auctor augue mauris. Scelerisque felis imperdiet proin fermentum leo vel. Faucibus et molestie ac feugiat. Proin sed libero enim sed faucibus turpis.

  </div>
</div>

CSS: CSS:

div#shopify-section-header .site-header {
  position: fixed;
  background-color: black;
  z-index:999;
  width:100%;
  top:0;
  left:0;
  height:100px;
}
div#shopify-section-header .site-header img{
  height:50px;
}
div#shopify-section-header .sticky-header{
  position:fixed;
  z-index:999;
  top:150px;
}
.content{
  margin-top:200px
}

Play around in this fiddle: https://jsfiddle.net/sztkujb2/10/ 在这个小提琴中玩耍: https : //jsfiddle.net/sztkujb2/10/

The code snippet doesn't contain all the resources and it's hard to understand the environment in which the navbar is used. code snippet不包含所有资源,并且很难理解使用navbar的环境。 This is a important detail and its very useful for developers. 这是一个重要的细节,对开发人员非常有用。

Today, I don't have anymore time to continue. 今天,我没有时间继续。 I plan to update my answer or maybe other developers will continue from where I left. 我打算更新答案,否则其他开发人员可能会从我离开的地方继续。


My approach for a solution is: 的解决方案是:

Notes : 注意事项

a) A sticky nav is already used, on large screens it display but only for the the menu elements. a)粘性导航已被使用,它在大屏幕上显示,但仅用于菜单元素。 I think the request is to make the entire nav bar sticky. 我认为要求是使整个导航栏保持粘性。
b) A solution is necessary for only for large screens(desktops), making the entire nav sticky b)仅适用于大屏幕(台式机)的解决方案是必需的,这会使整个导航系统变粘

1) Clone current HTML nav structure and append it after/before the original nav. 1) 克隆当前的HTML导航结构,并将其附加在原始导航之后/之前。 Without this, after the original nav is sticky( position: fixed ), the content will go upwards. 如果没有此功能,则在原始导航粘滞( position: fixed )之后,内容将向上移动。
2) After scroll certain distance, add a CSS class to the orignal nav with sticky rules. 2) 滚动一定距离后,使用粘性规则将CSS class添加到原始nav (#style #UX) I would decrease size of certain elements in order to leave more visible space. (#style #UX)我会减小某些元素的大小,以便留出更多可见空间。
3) Show ( visibility : hidden ) the cloned nav structure. 3) 显示visibility : hidden )克隆的导航结构。

Current code: 当前代码:

.sticky-header-structure-on #shopify-section-header{
    position : absolute;
}

.sticky-header-structure-on #shopify-section-header {
    position : fixed;
    width    : 100%;
    z-index  : 1;
    top      : 0;
}

/* Reset previous class for sticy menu element */
.sticky-header-structure-on #shopify-section-header .nav-bar.sticky-header,
.sticky-header-structure-on #shopify-section-header-clone .nav-bar.sticky-header{
  position : static;
  width    : auto;
}

#shopify-section-header-clone {
    display    : block!important;
    visibility : hidden;
}



var $body                             = $("body"),
    $sectionHeader        = $("#shopify-section-header"),
    $sectionHeaderClone   = $sectionHeader.clone(),
    $navBar                           = $sectionHeader.find(".nav-bar");

$sectionHeaderClone.css("display", "none");
$sectionHeaderClone.attr("id", "shopify-section-header-clone");
$sectionHeaderClone.insertAfter( $sectionHeader );

$(window).on("scroll", function() {
  debugger;

  // Only for medium and large screens - when the large meniu is active
  // As in the CSS @media
  if( window.innerWidth <= 768 ) {
     return;
  }


  if( $navBar.hasClass("sticky-header")  ) {
    $body.addClass("sticky-header-structure-on");
  } else {
    $body.removeClass("sticky-header-structure-on");
  }
});

After seeing your live code, I have added this and tested it: 看完您的实时代码后,我添加了此代码并对其进行了测试:

div#shopify-section-header {
    position: fixed;
    width: 100%;
    display: block;
    z-index: 999;
}

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

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