【问题标题】:Sticky position of nav change background at scroll position导航在滚动位置更改背景的粘性位置
【发布时间】:2020-04-28 09:20:30
【问题描述】:

我希望 <nav> 用 3 个数字固定。当它到达绿色方块时,它应该越过数字并保持固定并变成红色。当你回到顶部时,它应该回到原来的位置并回到绿色。我将如何实现这一目标?

.container {
  height: 1000px;
}

nav{
  display: flex;
  justify-content: space-around;
}

.square{
  background-color: green;
  width: 100px;
  height: 100px;
  margin: auto;
  display: block;
  position: sticky;
}
<div class="container">
  <header>
    <nav>
      <p>1</p>
      <p>2</p>
      <p>3</p>
    </nav>
  </header>
  <div class="square"></div>
</div>

【问题讨论】:

    标签: javascript css navigation nav sticky


    【解决方案1】:

    您可以使用javascript 来检测滚动并使用window.onscroll 为您的元素添加粘性类,还请注意,当使用sticky CSS 属性值进行显示时,您还应该调整位置,我使用了calc要计算左值,这里是一个有效的 sn-p:

    window.onscroll = function() {myFunction()};
    
    var header = document.querySelector(".square");
    var sticky = header.offsetTop;
    
    function myFunction() {
      if (window.pageYOffset > sticky) {
        header.classList.add("sticky");
      } else {
        header.classList.remove("sticky");
      }
    }
    .container {
      height: 10000px;
    }
    
    nav {
      display: flex;
      justify-content: space-around;
    }
    
    .square {
      background-color: green;
      width: 100px;
      height: 100px;
      margin: auto;
      display: block;
    }
    
    .sticky {
      position: fixed;
      top: 0;
      background-color:red;
      left: calc((100% - 100px)/2);
    }
    
    .sticky + .content {
      padding-top: 102px;
    }
    <!DOCTYPE html>
    <html>
    <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
    
    <div class="container">
      <header>
        <nav>
          <p>1</p>
          <p>2</p>
          <p>3</p>
        </nav>
      </header>
    
    
      <div class="square"></div>
    
    </div>
    </body>
    </html>

    【讨论】:

      【解决方案2】:

      要改变背景颜色,你需要以动画的方式查看,但是,根据定位,你需要添加top: 0之类的东西来设置你的组件将在什么位置粘。

      【讨论】:

        猜你喜欢
        • 2022-01-21
        • 2023-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多