문제

I found several solutions for my problem but I can't get anyone to work. I'm trying to smooth scroll to a tab when a link is clicked. That works perfectly. The problem is that when I have multiple links on a page that points to to a tab, only the link works which have a tab active. So when I click a link and that tab isn't active the link doesn't work.

So what I try to do is to make a tab active when I click a link.

What I have:

<a class="goSmoothly" href="#" data-target="description" onclick="return false">Link to tab1</a>
<a class="goSmoothly" href="#" data-target="specs" onclick="return false">Link to tab2</a>

<ul class="nav-tabs">
  <li class="active"><a href="#description" data-toggle="tab">Tab1</a></li>
  <li><a href="#specs" data-toggle="tab">Tab2</a></li>
</ul>


$( '.goSmoothly' ).on('click', function(event) {
    event.preventDefault();
    var target = "#" + $(this).data('target');

    $('html, body').animate({
      scrollTop: ($(target).offset().top - 150)
    }, 1200);

    var self = $(this), className = "active";
    self.addClass(className).siblings("."+className).removeClass(className);
  });
도움이 되었습니까?

해결책

The problem is this part:

var target = "#" + $(this).data('target');

$('html, body').animate({
  scrollTop: ($(target).offset().top - 150)
}, 1200);

Your $(target) selector is selecting an element with the id attribute of either description or specs, however in your code you have no elements with those IDs. Instead you have elements with those href attributes, which you can select instead using:

var target = $(this).data('target');

$('html, body').animate({
  scrollTop: ($('[href="' + target + '"]').offset().top - 150)
}, 1200);

Also rather than calling:

self.addClass(className).siblings("."+className).removeClass(className);

You can simply:

$('.active').removeClass('active');
$(this).addClass('active');
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top