2

Доброго времени суток!

Ситуация такова: есть меню на лэндинге, в котором при скролле страницы вниз появляется подсветка на активном пункте меню. Но есть одно но - это подсветка сразу же пропадает после того, как этот элемент проскроллен.

Вот js, с помощью которго это реализовано:

var menu_selector = ".menu-menu-container"; 
function onScroll(){
	var scroll_top = jQuery(document).scrollTop();
	jQuery(menu_selector + " a").each(function(){
		var hash = jQuery(this).attr("href");
		var target = jQuery(hash);
		if (target.position().top <= scroll_top && target.position().top + target.outerHeight() > scroll_top) {
			jQuery(menu_selector + " a.active").removeClass("active");
			jQuery(this).addClass("active");
		} else {
			jQuery(this).removeClass("active");
		}
	});
}

Вопрос - можно ли сделать так, чтобы после прокрутке этого элемента, подсветка на пункте меню оставалсь до тех пор, пока не начнется следующий пункт меню? Если можно, прошу дать ответ поподробнее, т.к. в js (и в jQuery в частности) не силен.

2 ответа 2

1

Я тоже в jQ не силен, но совершенно очевидно, что нужно менять условие

target.position().top <= scroll_top && target.position().top + target.outerHeight() > scroll_top
1
1

Зачем изобретать велосипед? Вот есть отличная реализация того, что вам нужно.
Автора, правда, не знаю.

(function() {
  /* Фиксация меню при прокрутке */
  $('.header-menu-wrp')
    .addClass('original')
    .clone()
    .insertAfter('.header-menu-wrp')
    .addClass('cloned')
    .removeClass('original');

  function resizeMenu() {
    var $original = $('.header-menu-wrp.original');
    var $cloned = $('.header-menu-wrp.cloned');

    if ($(window).scrollTop() >= ($original.offset().top)) {
      $cloned.css({
        'top': 0,
        'width': $original.css('width'),
        'display': 'block',
        'left': $original.offset().left + 'px'
      });
      $original.css('visibility', 'hidden');
    } else {
      $cloned.css('display', 'none');
      $original.css('visibility', 'visible');
    }
  }

  $(window).scroll(function() {
    resizeMenu();
  });

  $(window).resize(function() {
    resizeMenu();
  });

  /* Выделение активных пунктов меню */
  var last_id;
  var $top_menu = $('.header-menu-wrp.cloned');
  var menu_height = $top_menu.outerHeight(true);
  var $menu_items = $top_menu.find('a');
  var $scroll_items = $menu_items.map(function() {
    var item = $($(this).attr('href'));
    if (item.length) {
      return item;
    }
  });

  $menu_items.click(function(e) {
    var href = $(this).attr('href'),
      offset_top = href === '#' ? 0 : $(href).offset().top - menu_height;
    $('html, body').stop().animate({
      scrollTop: offset_top
    }, 300);
    e.preventDefault();
  });

  $(window).scroll(function() {
    var from_top = $(this).scrollTop() + menu_height;
    var mar = parseInt($top_menu.css('margin-bottom'));
    var cur = $scroll_items.map(function() {
      if ($(this).offset().top < from_top + mar) {
        return this;
      }
    });
    cur = cur[cur.length - 1];
    var id = cur && cur.length ? cur[0].id : '';
    if (last_id !== id) {
      last_id = id;
      $menu_items.parent()
        .removeClass('active')
        .end()
        .filter("[href='#" + id + "']")
        .parent()
        .addClass('active');
    }
  });
})();
.wrp {
  width: 600px;
  margin: 0 auto;
}

.header {
  height: 50px;
  text-align: center;
  border: 1px dashed #ddd;
  padding: 50px 0;
  margin: 20px 0;
  font-size: 18px;
}

.block {
  text-align: center;
  border: 1px dashed #ddd;
  padding: 100px 0;
  margin-bottom: 20px;
  font-size: 18px;
  background: #eeeeee;
}

.header-menu-wrp {
  height: 40px;
  line-height: 40px;
  width: 100%;
  background: #f48221;
  color: white;
  margin-bottom: 20px;
}

.header-menu-wrp.cloned {
  position: fixed;
  top: 0;
  margin-top: 0;
  z-index: 9999;
  display: none;
}

.header-menu {
  width: 100%;
  display: table;
  border-left: 1px solid #ffa44c;
}

.header-menu ul {
  display: table-row;
}

.header-menu li {
  display: table-cell;
  float: none;
  border-right: 1px solid #ffa44c;
}

.header-menu li.active {
  background: orange;
}

.header-menu li a {
  display: block;
  color: #fff;
  text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrp">
  <div class="header"></div>
</div>

<div class="header-menu-wrp">
  <div class="wrp">
    <div class="header-menu">
      <ul>
        <li><a href="#block-1">Блок 1</a></li>
        <li><a href="#block-2">Блок 2</a></li>
        <li><a href="#block-3">Блок 3</a></li>
        <li><a href="#block-4">Блок 4</a></li>
      </ul>
    </div>
  </div>
</div>

<div class="wrp">
  <div id="block-1" class="block">Блок id="block-1"</div>
  <div id="block-2" class="block">Блок id="block-2"</div>
  <div id="block-3" class="block">Блок id="block-3"</div>
  <div id="block-4" class="block">Блок id="block-4"</div>
</div>

Ваш ответ

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

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