【问题标题】:the hash link not matched with nav menu哈希链接与导航菜单不匹配
【发布时间】:2021-05-08 17:56:15
【问题描述】:

当我单击导航栏项时,哈希链接滚动事件与正确的导航菜单项不匹配 我试图向上或向下更改“scrollto”变量,但问题仍然存在

下面是代码:

// Smooth scroll for the menu and links with .scrollto classes
  var scrolltoOffset = $('#header').outerHeight() - 21;
  var clicked = false;
  $('.nav-menu a, #mobile-nav a, .scrollto').on('click', function(e) {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
      var target = $(this.hash);
      debugger;
      if (target.length) {
        e.preventDefault();

        var scrollto = target.offset().top - scrolltoOffset;
        if ($(this).attr("href") == '#header') {
          scrollto = 0;
        }

        $('html, body').animate({
          scrollTop: scrollto
        }, 1500, 'easeInOutExpo');

        if ($(this).parents('.nav-menu').length) {
          $('.nav-menu .menu-active').removeClass('menu-active');
          $(this).closest('li').addClass('menu-active');
        }

        if ($('body').hasClass('mobile-nav-active')) {
          $('body').removeClass('mobile-nav-active');
          $('#mobile-nav-toggle i').toggleClass('fa-times fa-bars');
          $('#mobile-body-overly').fadeOut();
        }
       
        return false;
      }
    }
  });

这是直播网站innovators.com

【问题讨论】:

  • 如果我的答案适合你,你能接受吗?

标签: javascript jquery css dom event-handling


【解决方案1】:

轻松修复。你滚动的不够多。 只需少滚动两个像素:-21 => -23

// Smooth scroll for the menu and links with .scrollto classes
  var scrolltoOffset = $('#header').outerHeight() - 23;
  var clicked = false;
  $('.nav-menu a, #mobile-nav a, .scrollto').on('click', function(e) {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
      var target = $(this.hash);
      debugger;
      if (target.length) {
        e.preventDefault();

        var scrollto = target.offset().top - scrolltoOffset;
        if ($(this).attr("href") == '#header') {
          scrollto = 0;
        }

        $('html, body').animate({
          scrollTop: scrollto
        }, 1500, 'easeInOutExpo');

        if ($(this).parents('.nav-menu').length) {
          $('.nav-menu .menu-active').removeClass('menu-active');
          $(this).closest('li').addClass('menu-active');
        }

        if ($('body').hasClass('mobile-nav-active')) {
          $('body').removeClass('mobile-nav-active');
          $('#mobile-nav-toggle i').toggleClass('fa-times fa-bars');
          $('#mobile-body-overly').fadeOut();
        }
       
        return false;
      }
    }
  });

【讨论】:

  • 不,这并不能解决我已经尝试过的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-27
  • 2013-05-19
  • 2013-08-20
  • 2014-05-19
  • 2021-04-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多