【问题标题】:How can I add a transition to my sticky navbar width when it gets sticky?当它变得粘滞时,如何向我的粘滞导航栏宽度添加过渡?
【发布时间】:2022-04-08 00:17:19
【问题描述】:

我目前正在构建一个直接位于页面内容中的粘性导航栏。内容的每一侧都有一点填充。

当我滚动出视口时,我的 jQuery 函数使我的导航栏变得粘滞。由于它的宽度为100%,因此它的大小变化确实不太可能,这让用户感觉有些事情没有经过深思熟虑。

为了让它看起来更好,我尝试使用transition: width .2s,但宽度没有任何成功。我认为这并不容易,因为初始宽度已经是100%...

这个想法是让宽度在两个方向上变化,让它看起来更好一点:

(function($) {
  $(document).ready(function() {
    let nav = $('#nav');
    let navOffsetTop = nav.offset().top;

    $(window).scroll(function() {
      if ($(this).scrollTop() >= navOffsetTop) {
        nav.addClass('sticky');
      } else {
        nav.removeClass('sticky');
      }
    });
  });
})(jQuery);
#page {
  width: 100%;
  padding-left: 50px;
  padding-right: 50px;
  box-sizing: border-box;
}

#container {
  background: green;
  width: 100%;
  height: 1500px;
}

#nav {
  height: 60px;
  width: 100%;
  background-color: red;
  margin-bottom: 30px;
  z-index: 1;
  transition: width .2s ease;
}

#nav.sticky {
  position: fixed;
  top: 0;
  left: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="page">
  <h1>Hello</h1>
  <div id="nav"></div>
  <div id="container">
  </div>
</div>

【问题讨论】:

  • 如果你不想让你的导航栏全宽,你可以使用 "position:sticky;"在“位置:固定;”以外的“#nav.sticky”元素上
  • 这就是我在示例中所做的 ;)

标签: html jquery css


【解决方案1】:

在容器中,使用宽度作为百分比并将边距自动调整为居中。

然后添加一个同时向左导航并完全填充宽度的动画。

(function($) {
  $(document).ready(function() {
    let nav = $('#nav');
    let navOffsetTop = nav.offset().top;

    $(window).scroll(function() {
      if ($(this).scrollTop() >= navOffsetTop) {
        nav.addClass('sticky');
      } else {
        nav.removeClass('sticky');
      }
    });
  });
})(jQuery);
* {
  padding: 0;
  margin: 0;
}

#page {
  width: 100%;
  box-sizing: border-box;
}

#container {
  background: green;
  width: 90%;
  height: 1500px;
  margin: auto;
}

#nav {
  height: 60px;
  width: 90%;
  max-width: 100%;
  background-color: red;
  z-index: 1;
  margin: auto;
  margin-bottom: 30px;
  transition: 0.5s all;
}

#nav.sticky {
  position: fixed;
  top: 0;
  width: 100%;
  animation-duration: .5s;
  animation-name: smooth;
}

@keyframes smooth {
  from {
    left: 5%;
  }
  to {
    left: 0%;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="page">
  <h1>Hello</h1>
  <div id="nav"></div>
  <div id="container">
  </div>
</div>

【讨论】:

  • 页面的宽度是预定义的。如果我改变它,我会破坏很多默认功能......
  • 屏幕有不同的分辨率。你应该可以调整它。使用像素,您无法为所有像素创建动画。因为通过设置固定位置,您实际上是浮动元素。
猜你喜欢
  • 2019-05-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-14
  • 2016-07-31
  • 1970-01-01
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多