简体   繁体   中英

Related UL blocks by LI elements

I don't even know how to formulate this question... I have 2 UL blocks, each has 10 LI elements, they always going to have the same number of elements, 10, 160, 12, etc., Left block is a floating fixed navigation, and the right block has the content, how do I know know which element is on view so on the left block I add a class as current

<div class="leftnav">
<ul class="navigation">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
    <li>6</li>
</ul>
</div>

<ul>
   <li>Content 1</li>
   <li>Content 2</li>
   <li>Content 3</li>
   <li>Content 4</li>
   <li>Content 5</li>
   <li>Content 6</li>
</ul>

So when a user scroll down content 2 show up and navigation li get a class as current... when user clicks on the navigation it scrolls to the content on the right... does anyone know how to do this?

Based on the information being dynamic and assuming you can't or don't want to affect the markup, how about....

$(window).on('scroll', handleScroll);

function handleScroll (e) {
  var currentLiIndex;
  $('{second ul} li').each(function (i, e) { 
    // loop through all the second li's, 
    // find which is closest to top of the window but below the scroll
    if ($(e).offset().top > scrollY) {
      currentLiIndex = i;
      return false;
    }
  });

  // clear actives
  $(".navigation li").removeClass('active');

  // target the nav li based on the index of the top function
  // and add active class
  $(".navigation li")[currentLiIndex].addClass('active');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM