滚动到href属性时删除类

时间:2016-06-30 20:40:14

标签: javascript jquery

目前我从2000年的元素中删除了类

setTimeout(function(){
        $('.nav-item a').removeClass('active');
}, 2000);

如何在'autoscroll'完成后修改我的代码以删除类?

  $('.nav-item a, .nav-brand a, .button, .footer2 a').click(function() {
event.preventDefault(); // default action of the event will not be triggered, eg will not change links name
var windowSize = $(window).width();
if (windowSize >= 769) {
  $('html, body').animate({
    scrollTop: $($(this).attr('href')).offset().top - 51
  }, 1500);
}
else if (windowSize <= 768) {
  $('html, body').animate({
    scrollTop: $($(this).attr('href')).offset().top - 102
  }, 1500);
}
return false; });

我想我应该以某种方式使用attribute href,但我不确定如何。

2 个答案:

答案 0 :(得分:2)

您可以通过定义animate方法的完整回调来实现。

$('.nav-item a, .nav-brand a, .button, .footer2 a').click(function() {
  event.preventDefault(); // default action of the event will not be triggered, eg will not change links name
  var windowSize = $(window).width();
  var scrollY;

  if (windowSize >= 769) {
    scrollY = $($(this).attr('href')).offset().top - 51;
  } else {
    scrollY = $($(this).attr('href')).offset().top - 102;
  }

  $('html, body').animate({
    scrollTop: scrollY
  }, 1500, function() {
    $('.nav-item a').removeClass('active');
  });

  return false;
});

答案 1 :(得分:1)

JQuery Animate采用最终参数完整的函数,因此您应该可以编写如下内容:

$('.nav-item a, .nav-brand a, .button, .footer2 a').click(function() {
  event.preventDefault();
  var windowSize = $(window).width();
  if (windowSize >= 769) {
    $('html, body').animate({
      scrollTop: $($(this).attr('href')).offset().top - 51
    }, 1500, function() {
      $('.nav-item a').removeClass('active');
    });
  } else if (windowSize <= 768) {
    $('html, body').animate({
      scrollTop: $($(this).attr('href')).offset().top - 102
    }, 1500, function() {
      $('.nav-item a').removeClass('active');
    });
  }
  return false;
});