HTML 实现锚点滑动 或者点击不同的tab时添加下划线并滑动到对应的盒子,手动滑动下划线也随位置变动

1、之前有写的vue的,方法跟这个大致相同,有兴趣的可以看看vue 实现类似于锚点滑动 或者点击不同的tab时添加下划线并滑动到对应的盒子,手动滑动下划线也随位置变动-CSDN博客
2、这里有两种方式,但是第一种方式存在弊端,就是当我们顶部的导航栏是固定定位,滑动到对应的视口位置,有一部分内容被压住了,就是滑过了,这个时候我们就要用第二种方式,第二种方式可以灵活的根据导航栏的高度去调节,以便滑动到对应的盒子可以完整展现出来
3、内容跟样式部分是通用的,只有JS部分有区别
4、html 结构 ,如果对应你帮助,记得点赞
<ul id="nav-list" class="tabsul">
   <li class="liTem  active" data-target="section1">首页</li>
   <li class="liTem" data-target="section2">服务内容</li>
   <li class="liTem" data-target="section3">业务案例</li>
   <li class="liTem" data-target="section4">关于我们</li>
   <li class="liTem" data-target="section5">联系方式</li>
</ul>
<div class="section1 section" id="section1"></div>
<div class="section2 section" id="section2"></div>
<div class="section3 section" id="section3"></div>
5、css部分
 .tabsul {
      display: flex;
      line-height: 30px;
      justify-content: space-between;
      list-style-type: none;
    }

    .liTem {
      margin: 50px;
      padding: 0 0px 5px 0px;
      box-sizing: border-box;
      height: 35px;
      text-align: center;
      font-size: 16px;
      font-weight: 500;
      margin: 0 20px;
      cursor: pointer;
      list-style-type: none;
      position: relative;
    }
    .liTem.active::after {
      content: "";
      position: absolute;
      width: 100%;
      height: 2px;
      bottom: 0;
      left: 0;
      border-bottom: 3px #ff8000 solid;
    }
.section1 {
      width: 100%;
      height: 600px;
      color: #fff;
      font-size: 30px;
      font-weight: 600;
      display: flex;
    }
.section2 {
      width: 100%;
      height: 400px;
      color: #fff;
      font-size: 30px;
      font-weight: 600;
      display: flex;
    }
.section3 {
      width: 100%;
      height: 700px;
      color: #fff;
      font-size: 30px;
      font-weight: 600;
      display: flex;
    }
6、JS部分,这是第一种方法
document.addEventListener("DOMContentLoaded", function  () {
      const navList = document.getElementById('nav-list');
      const sections = document.querySelectorAll('.section');
      let timeout;
      let activeElement = document.querySelector('.liTem');
      activeElement.classList.add('active');
      navList.addEventListener('click', function (e) {
        if (e.target.classList.contains('liTem')) {
          e.preventDefault(); // 阻止默认行为
          const targetId = e.target.getAttribute('data-target');
          const targetElement = document.getElementById(targetId);
          clearTimeout(timeout);
          if (activeElement !== e.target) {
            // activeElement.classList.remove('active');
            // e.target.classList.add('active');
            e.preventDefault(); // 阻止默认行为
            activeElement = e.target;
            timeout = setTimeout(() => {
              targetElement.scrollIntoView({
                behavior: 'smooth',
                block: 'start',
              })
            }, 100);
          }
        }
      });

      window.addEventListener('scroll', function () {
        let fromTop = window.scrollY;
        sections.forEach(function (section) {
          if (section.offsetTop <= fromTop && section.offsetTop + section.offsetHeight > fromTop) {
            document.querySelectorAll('.liTem').forEach(item => item.classList.remove('active'));
            document.querySelector(`[data-target=${section.id}]`).classList.add('active');
          }
        });
      });
    });

第二种方法

 const tabItems = document.querySelectorAll('.liTem');
  const sections = document.querySelectorAll('.section');

  tabItems.forEach(item => {
    item.addEventListener('click', function() {
      const targetId = this.getAttribute('data-target');
      const targetSection = document.getElementById(targetId);
      const offset = 100; // 滑动偏移量   这个就是可以改你对应的导航栏的高度,就是被遮住的部分

      const targetPosition = targetSection.offsetTop - offset;
      window.scrollTo({
        top: targetPosition,
        behavior: 'smooth'
      });
    });
  });

  window.addEventListener('scroll', function() {
    let fromTop = window.scrollY;

    sections.forEach(section => {
      if (fromTop >= section.offsetTop - 100) {
        let targetId = section.getAttribute('id');
        // 移除所有 tab 的 active 类
        tabItems.forEach(tabsul => tabsul.classList.remove('active'));
        // 给对应的 tab 添加 active 类
        document.querySelector(`[data-target="${targetId}"]`).classList.add('active');
      }
    });

    // 实时计算当前页面位置,确定应该添加下划线的 liTem
    let currentPosition = window.scrollY + 100;
    tabItems.forEach(tabsul => {
      let targetId = tabsul.getAttribute('data-target');
      let targetSection = document.getElementById(targetId);
      if (currentPosition >= targetSection.offsetTop && currentPosition < targetSection.offsetTop + targetSection.offsetHeight) {
        tabItems.forEach(tabsul => tabsul.classList.remove('active'));
        tabsul.classList.add('active');
      }
    });
  });

  • 10
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个使用 jQuery 实现的侧边栏导航滑动对应导航会跟着改变颜色,点击也可以跳转到对应内容的示例代码: HTML: ```html <div class="sidebar"> <ul> <li><a href="#section1">Section 1</a></li> <li><a href="#section2">Section 2</a></li> <li><a href="#section3">Section 3</a></li> <li><a href="#section4">Section 4</a></li> </ul> </div> <div class="main-content"> <section id="section1"> <h2>Section 1</h2> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p> </section> <section id="section2"> <h2>Section 2</h2> <p>Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p> </section> <section id="section3"> <h2>Section 3</h2> <p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p> </section> <section id="section4"> <h2>Section 4</h2> <p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.</p> </section> </div> ``` CSS: ```css .sidebar { position: fixed; top: 0; left: 0; width: 200px; height: 100%; background-color: #f1f1f1; } .main-content { margin-left: 200px; } .sidebar ul { list-style-type: none; margin: 0; padding: 0; } .sidebar li { margin: 10px 0; } .sidebar a { display: block; padding: 10px; color: #000; text-decoration: none; } .sidebar a.active { background-color: #ccc; } .main-content section { padding: 50px; margin-top: 70px; background-color: #fff; box-shadow: 0 0 5px rgba(0, 0, 0, 0.2); } ``` JavaScript: ```javascript $(document).ready(function() { // 高亮当前导航 var sections = $('section'), nav = $('.sidebar'), nav_height = nav.outerHeight(); $(window).on('scroll', function() { var cur_pos = $(this).scrollTop(); sections.each(function() { var top = $(this).offset().top - nav_height, bottom = top + $(this).outerHeight(); if (cur_pos >= top && cur_pos <= bottom) { nav.find('a').removeClass('active'); sections.removeClass('active'); $(this).addClass('active'); nav.find('a[href="#'+$(this).attr('id')+'"]').addClass('active'); } }); }); // 平滑滚动到锚点 $('a').on('click', function(e) { if (this.hash !== '') { e.preventDefault(); var hash = this.hash; $('html, body').animate({ scrollTop: $(hash).offset().top - nav_height }, 800, function() { window.location.hash = hash; }); } }); }); ``` 代码解释: 1. 在 HTML 中,我们使用 `<div class="sidebar">` 元素包裹侧边栏导航,使用 `<div class="main-content">` 元素包裹主要内容,每个主要内容元素使用 `<section>` 标签。 2. 在 CSS 中,我们设置侧边栏导航的样式,包括固定在左侧、背景颜色、字体颜色等。 3. 在 JavaScript 中,我们使用 `$(document).ready()` 方法等待文档加载完成,然后执行以下操作: 1. 使用 `$(window).on('scroll', function() {...})` 监听滚动事件,当面滚动,高亮当前导航。 2. 使用 `$('a').on('click', function(e) {...})` 监听点击事件,当点击导航链接,平滑滚动到锚点。 这样就实现了一个简单的侧边栏导航滑动对应导航会跟着改变颜色,点击也可以跳转到对应内容的功能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值