简体   繁体   中英

Scroll a list up/down to a div

I have an unordered list with numbers listed. After, I have a div tag with the left and right arrow in it to indicate the current number selected. I have tried the following code, but it's not working.

My requirement is whenever any of the numbers are clicked the list should scroll slowly up/down to the position of div with id="icon" . How can I implement this?

 $('ul li').click(function() { alert("dfd"); $('html, body').animate({ scrollTop: $("#icon").offset().top }, 2000); }) 
 ul { list-style: none; } span { position: fixed; top: 50px; left: 35px } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> <span id="icon"><&nbsp; &nbsp;></span> 

https://jsfiddle.net/czjqf3p2/23/

Instead of animating the HTML/BODY, try animating the UL as in the below sample.

 $('ul li').click(function(){ var index=$(this).index(); var listPosition = -1*index*50; $('ul').animate({ top: listPosition }, 600); }) 
 ul { list-style:none; position: fixed; margin-top: 100px; } li{ height: 50px; line-height: 50px; } span{ position:fixed; top:0; left:35px; height: 50px; line-height: 50px; margin-top:100px; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> <span id="icon"> < &nbsp; &nbsp; > </span> 

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