jquery - 滚动到指定部分时如何在 href 上添加事件类?

标签 jquery html css

我正在尝试创建单页网站。现在,当滚动到指定的 部分 时,我正在尝试将事件类添加到我的 a 中。例如,当我滚动到 #services 时,我的 href 和 url #service 将变成这样

<a class="active" href="#services"><img height="22px" width="22px" src="assets/icon/tools.png">  <span> Service </span></a>

这是我的html

<div class="sidenav">
  <a href="#home"><img height="22px" width="22px" src="assets/icon/home.png"> <span> Home </span></a>
  <a href="#services"><img height="22px" width="22px" src="assets/icon/tools.png">  <span> Service </span></a>
  <a href="#portofolio"><img height="22px" width="22px" src="assets/icon/profiles.png"> <span> Portofolio </span></a>
  <a href="#about"><img height="22px" width="22px" src="assets/icon/info.png">  <span> About Us </span></a>
  <a href="#contact"> <img height="22px" width="22px" src="assets/icon/customer-service.png"> <span> Contact Us </span></a>
</div> 

    <div class="main">

    <section id="home">  Main </section> 
    <section id="services">  Services </section> 
    <section id="portofolio">  Portofolio </section> 
    <section id="about">  About Us</section> 
    <section id="contact">  Contact Us </section> 

    </div>

这是我的js

$(document).ready(function(){

        var before;

      $("a").on('click', function(event) {

        if (this.hash !== "") {
          event.preventDefault();
          var hash = this.hash;
          $('html, body').animate({
            scrollTop: $(hash).offset().top
          }, 800, function(){
            window.location.hash = hash;
          });
        }
      });

      $("a").click(function(){
            if(before){
                before.removeClass("active");
            }

            $(this).addClass("active");
            before = $(this);
      });

});

我已经尝试过这种方式,但现在我遇到了很多问题

var sections = $('section')
      , nav = $('.sidenav')
      , 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');
        }
      });
    });

第一个问题,但是当我进入第一部分时,我的href 没有active class,第二个问题是当我在任何部分时链接具有到下一节的链接的 active

enter image description here

最佳答案

您可能想尝试 Scrollorama jQuery 插件

关于jquery - 滚动到指定部分时如何在 href 上添加事件类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53330559/

相关文章:

jquery - Bootstrap 下拉崩溃,

javascript - jquery:将一组元素粘贴到另一组元素/合并元素上

javascript - 如何从 Kendo-multiSelect 中获取选定值?

html - Jumbotron 破坏了移动网站上的导航栏

javascript - wymeditor - 在样式表中格式化标题

css - Liferay 中的自定义导航菜单?

html - 缩进表格边框

javascript - html2canvas + FileSaver 浏览器问题

html - Bootstrap 4 轮播 - 响应行为

html - 如何使用 Skeleton CSS 创建固定侧边栏?