1

Eсть такая структура страницы

$('#sectione_one').on('inview', function(event, isInView) {
  if (isInView) {
    $('.aside a').addClass('active');
    console.log('вижу')
  } else {
    $('.aside a').removeClass('active');
    console.log('не вижу')
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="wrapper">
  <div class="aside">
    <a href="#sectione_one"></a>
    <a href="#sectione_two"></a>
    <a href="#sectione_three"></a>
    <a href="#sectione_four"></a>
    <a href="#sectione_five"></a>
  </div>
  <div class="content">
    <section id="sectione_one"></section>
    <section id="sectione_two"></section>
    <section id="sectione_three"></section>
    <section id="sectione_four"></section>
    <section id="sectione_five"></section>
  </div>
</div>

Навигационое меню .aside фиксировано слева.

Надо сделать, что бы при скролле, если видно в поле зрение браузера, соответствующая ссылка a получала класс active, где id страницы и hrefссылки совпадают

Так вот скрипт( с использование библиотеки)

Тут когда дохожу до секции #reviews, то a из aside получает класс active. Проблема в том, что сейчас получает все ссылки получают класс active. Мне же надо добавить класс только ссылке, которая совпадает с id секции. Так же не могу понять, как сделать, чтобы скрипт работал для всех секций и ссылок меню, а не для каждой в отдельности.

1
  • $('.aside a[href="#sectione_one"]').toggleClass('active', isInView); ?
    – teran
    17 янв 2018 в 14:23

2 ответа 2

0

$(document).scroll(function() {
  $('section').each(function() {
    $('a[href=#' + $(this).attr('id') + ']').removeClass('active');
    if (isVisible($(this), $(window))) {
      $('a[href=#' + $(this).attr('id') + ']').addClass('active');
    }
  });
});

function isVisible(row, container) {
  var elementTop = $(row).offset().top,
    elementHeight = $(row).height(),
    containerTop = container.scrollTop(),
    containerHeight = container.height();
  return ((((elementTop - containerTop) + elementHeight) > 0) && ((elementTop - containerTop) < containerHeight));
}
.aside {
  position: fixed;
  left: 0;
  top: 0
}

.aside a {
  display: block
}

.content section {
  height: 500px;
  border: 1px solid #000;
  text-align: right
}

.active {
  color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="aside">
    <a href="#sectione_one" class="active">sectione_one</a>
    <a href="#sectione_two">sectione_two</a>
    <a href="#sectione_three">sectione_three</a>
    <a href="#sectione_four">sectione_four</a>
    <a href="#sectione_five">sectione_five</a>
  </div>
  <div class="content">
    <section id="sectione_one">sectione_one</section>
    <section id="sectione_two">sectione_two</section>
    <section id="sectione_three">sectione_three</section>
    <section id="sectione_four">sectione_four</section>
    <section id="sectione_five">sectione_five</section>
  </div>
</div>

0

Потенциально, ваш код должен принимать следующий вид:

$('.content section').on('inview', function(event, isInView) {
     var sId = $(this).attr("id");

     $(".aside a[href='#" + sId + "']").toggleClass('active', isInview);
});

Проблема возникнет, когда в экран будет влезать, например, сразу два section. В таком случае можно получить, что в меню, активными можно получить сразу два пункта.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.