js计算滚轮滚动到导航组件时吸顶

本文介绍了一种使用JavaScript实现网页导航栏吸顶效果的方法。当页面滚动到一定距离时,导航栏会固定在顶部;反之则恢复相对定位。文章提供了完整的HTML、CSS和JS代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

吸顶方法:

// 吸顶
const scroll = function () {
  if (document.body.scrollTop >= 300 || document.documentElement.scrollTop >= 300) {
    document.querySelector('.nav').style.position = 'fixed'
    document.querySelector('.nav').style.top = '0'
  } else if (document.body.scrollTop <= 300 || document.documentElement.scrollTop <= 300) {
    document.querySelector('.nav').style.position = 'relative'
    document.querySelector('.nav').style.top = '300px'
  }
}

调用:

window.onscroll = document.body.onscroll = scroll

代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<style>
  body {
    width: 100%;
    min-height: 200vh;
    position: relative;
    padding: 0;
    margin: 0;
  }
  .nav {
    /* position: fixed; */
    position: relative;
    top: 300px;
    width: 100%;
    height: 50px;
    background-color: rgb(40, 128, 101);
  }
</style>
<body>
  <div class="nav"></div>
</body>
<script>
// 吸顶
const scroll = function () {
  if (document.body.scrollTop >= 300 || document.documentElement.scrollTop >= 300) {
    document.querySelector('.nav').style.position = 'fixed'
    document.querySelector('.nav').style.top = '0'
  } else if (document.body.scrollTop <= 300 || document.documentElement.scrollTop <= 300) {
    document.querySelector('.nav').style.position = 'relative'
    document.querySelector('.nav').style.top = '300px'
  }
}

// document.body.addEventListener('scroll', scroll, false)
window.onscroll = document.body.onscroll = scroll
</script>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值