Sticky Header 的两种实现方式

Header 默认显示在页面中,滑到某个位置时 sticky(CodePen预览
<p style="margin-bottom:100px;">Scroll this page.</p>
<div class="sticky">
  <h3>Super amazing header</h3>
</div>
<p style="margin-top:500px;">Still there?</p>
<p style="margin-top:500px;">Yep!</p>
<p style="margin-top:500px;">Scroll so hard!</p>
body {
  margin: 0;
  text-align: center;
  font-family: sans-serif;
}
.fixed {
  position: fixed;
  top: 0;
}
.sticky {
  width: 100%;
  background: #f6d565;
  padding: 25px 0;
  text-transform: uppercase;
}
const sticky = document.querySelector(".sticky");
const origOffsetY = sticky.offsetTop;

function onScroll() {
  sticky.classList.toggle("fixed", window.scrollY >= origOffsetY);
}

document.addEventListener("scroll", onScroll);

Header 默认不显示,滑到某个位置时显示并 sticky(CodePen预览
<div class="wrap"></div>
<div class="pin">hello</div>
* {
  margin: 0;
  padding: 0;
}
.wrap {
  height: calc(100vh + 100px);
  background-color: pink;
}
.pin {
  width: 100%;
  height: 50px;
  position: fixed;
  top: -50px;
  left: 0;
  transition: .3s all;
  transform: translateZ(0);
  background-color: rgba(0, 0, 0, .5);
  visibility: hidden;
}
.pin.show {
  top: 0;
  visibility: visible;
}
const pin = document.querySelector('.pin');

function onScroll() {
  const scrollY = window.scrollY;
  pin.classList.toggle('show', scrollY >= 50);
}

window.addEventListener('scroll', onScroll);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值