简体   繁体   中英

nth link scroll to nth li in the same order

I have a set of links :

<div id="links">
<a>A</a>
<a>B</a>
<a>C</a>
…
</div>

And in the same page also I have a set of tabs:

<ul id="target">
<li>#1</li>
<li>#2</li>
<li>#3</li>
….
</ul>

how can I make the first < a>(A) scroll to the first < li>(#1) and the second < a>(B) scroll to the second < li>(#2) and the third < a>(C) scroll to the third < li>(#3) and so on …….

Note: The number of links and its targets not fixed It's dynamic, so I can't add id's to every item.

Add IDs to your list elements, and link them up.

<div id="links">
    <a href="#link_1">A</a>
    <a href="#link_2">B</a>
    <a href="#link_3">C</a>

<ul id="target">
    <li id="link_1">#1</li>
    <li id="link_2">#2</li>
    <li id="link_3">#3</li>
</ul>

Granted, this solution does not animate the scrolling, so you jump to the location in the document. Adding a jQuery plugin that adds scrolling animation should work without changing the code, though.

Just add id's to every item.

 $(document).on('click', 'a', function(event) { event.preventDefault(); $('html, body').animate({ scrollTop: $($.attr(this, 'href')).offset().top }, 500); }); 
 #links { height: 500px; } #target li { line-height: 300px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="links"> <a href='#1'>A</a> <a href='#2'>B</a> <a href='#3'>C</a> … </div> <ul id="target"> <li id='1'>#1</li> <li id='2'>#2</li> <li id='3'>#3</li> …. </ul> 

With jQuery, you could do something like this:

$('#links a').on('click', function () {
    //get the index of clicked a
    var index = $(this).index();

    //scroll to the li of equal index
    $('html, body').animate({
        scrollTop: $($("#target li").eq(index)).offset().top
    }, 500);
});

Here's a working example:

https://jsbin.com/ruwacejifi/edit?html,js,output

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