向下滚动页面时,如何使导航栏保持在顶部 [英] How do I make nav bar stick on top when you scroll down page

查看:91
本文介绍了向下滚动页面时,如何使导航栏保持在顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为某人做这个网站,并想知道如何让导航栏粘贴在桌面上并滚动页面?它作为响应就好了。任何帮助都会有所帮助,在此先感谢。



I am doing this site for someone and was wondering how to make the navigation bar sticky on desktop and scroll with the page ? It works as a responsive just fine. Any help would be helpful, thanks in advance.

<!DOCTYPE html>

body {margin:0;}

.topnav {
  overflow: hidden;
  background-color: #333;
}

.topnav a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
}

.topnav a:hover {
  background-color: #ddd;
  color: black;
}

.topnav .icon {
  display: none;
}

@media screen and (max-width: 600px) {
  .topnav a:not(:first-child) {display: none;}
  .topnav a.icon {
    float: right;
    display: block;
  }
}

@media screen and (max-width: 600px) {
  .topnav.responsive {position: relative;}
  .topnav.responsive .icon {
    position: absolute;
    right: 0;
    top: 0;
  }
  .topnav.responsive a {
    float: none;
    display: block;
    text-align: left;
  }

}





<div class="topnav" id="myTopnav">
    <a href="#home">Home</a>
    <a href="#contact">Accessories</a>
    <a href="#contact">Bras & Panties</a>
    <a href="#lingerie">Bridal</a>
    <a href="#contact">Costumes</a>
    <a href="#contact">Lingerie</a>
    <a href="#contact">Sleepwear</a>
    <a href="#contact">Swimwear</a>
    <a href="#">Adult Super Store</a>
  <a style="font-size: 15px" class="icon"></a>
</div>
<h1>
<a href="#" title="Welcome to the lingerie shop and more"></a>
</h1>
<div style="padding-left: 16px">
  <h2>Responsive Topnav Example</h2>
  <p>Resize the browser window to see how it works.</p>
</div>


function myFunction() {
    var x = document.getElementById("myTopnav");
    if (x.className === "topnav") {
        x.className += " responsive";
    } else {
        x.className = "topnav";
    }
}





我的尝试:



这是新手,所以不知道该怎么做才能让导航栏坚持滚动



What I have tried:

Am new to this so not sure what to try to make the nav bar stick on scroll

推荐答案

你可以用位置已修复州,

you can use position to fixed state,
.topnav {
  overflow: hidden;
  background-color: #333;
  position:fixed;
}


使用粘性定位:

我可以使用...... CSS位置:粘性 [ ^ ]

粘性定位| MDN [ ^ ]



现有代码所需的唯一更改:

Use "sticky" positioning:
Can I use... CSS position:sticky[^]
Sticky positioning | MDN[^]

The only change required to your existing code:
.topnav {
  overflow: hidden;
  background-color: #333;
  
  /* Add these two lines: */
  position: sticky;
  top: 0;
}

这篇关于向下滚动页面时,如何使导航栏保持在顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆