【问题标题】:scroll to top inside a scrollable div在可滚动的 div 内滚动到顶部
【发布时间】:2016-06-06 19:35:03
【问题描述】:

我在一个可滚动的 div 中有很多部分,如果单击,我会尝试将部分设置为顶部,第一次效果很好,但之后就不行了。这是我的尝试

$('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>

【问题讨论】:

  • 谢谢@Roko C. Buljan :)
  • padding-bottom:400px; 正在阻止您的 &lt;div class="test"&gt; 滚动,您最好将其从您的代码 sn-p 中删除。

标签: javascript jquery html css scroll


【解决方案1】:

您需要将.test 的当前scrollTop() 位置添加到您的数学中

$(".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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多