切换后 ScrollTop 不起作用

ScrollTop not working after toggle

无法理解,为什么它不滚动到元素。

<div class="h3 showhide">...</div>
<div id="comments" class="inv" style="display:none;">...</div>
<script type="text/javascript">
    $(document).ready(function () {
        $('.main-content').on('click', '.showhide', function () {
            $(".inv").toggle("slow");
            $('html, body').stop(true, true).animate({
                scrollTop: $('#comments').offset().top
            }, 500);
            return false;
        });
    });
</script>

Display:none 表示该元素在页面中没有位置。因此滚动不滚动。

参考:https://bugzilla.mozilla.org/show_bug.cgi?id=211236

您需要显示 #comments 才能使用 .show() 获得 .offset().top 然后使用 .hide() 隐藏它。

看这个例子:

<script type="text/javascript">
  $(document).ready(function() {
    var comments_top = $('#comments').show().offset().top;


    $('.main-content').on('click', '.showhide', function() {
      if ($('#comments').is(":hidden")) {
      comments_top = $('#comments').show().offset().top;
      $('#comments').hide();
    }
      $(".inv").toggle("slow");
      $('html, body').stop(true, true).animate({
        scrollTop: comments_top
      }, 500);
      return false;
    });
  });
</script>