简体   繁体   中英

scroll to top inside a scrollable div

I have many sections inside a scrollable div, I'm trying to animate the section to top if clicked, it works good the first time but not after that. this is my attempt

 $('p').click (function(){ $('.test').animate({scrollTop: $(this).offset().top}, 800); });
 .test{ overflow:auto; max-height:300px; width:300px; padding-bottom:400px; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="test"> <p>Section 1</p> <p>Section 2</p> <p>Section 3</p> <p>Section 4</p> <p>Section 5</p> <p>Section 6</p> <p>Section 7</p> <p>Section 8</p> <p>Section 9</p> <p>Section 10</p> <p>Section 11</p> <p>Section 12</p> <p>Section 13</p> <p>Section 14</p> <p>Section 15</p> </div>

You need to add the .test 's current scrollTop() position to your math

 $(".test").on("click", "p", function(evt) { var $test = $(evt.delegateTarget), // The ".test" parent element $p = $(this); // The clicked "p" element $test.stop().animate({ scrollTop: $p.offset().top + $test.scrollTop() }, 800); });
 body{margin:0;} .test{overflow:auto; height:200px; width:300px;}
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="test"> <p>Section 1</p> <p>Section 2</p> <p>Section 3</p> <p>Section 4</p> <p>Section 5</p> <p>Section 6</p> <p>Section 7</p> <p>Section 8</p> <p>Section 9</p> <p>Section 10</p> <p>Section 11</p> <p>Section 12</p> <p>Section 13</p> <p>Section 14</p> <p>Section 15</p> </div>

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