0

I have a table, representing a calendar, that can expand and collapse table rows.

  <tr class="parent" id="month1">
    <th class="subheader">Januari</th>
    <th></th><th></th>
  </tr>
  <tr class="row child-month1" id="day-1">
    <td class="date"> 1 januari 2010</td>
    <td>Bedrag </td>
    <td>-817.0 </td>
  </tr>
  <tr class="row child-month1" id="day-2">
    <td class="date"> 2 januari 2010</td>
    <td>Bedrag </td>
    <td> 0 </td>
  </tr>

With jQuery I make it clickable:

<script type="text/javascript">
$(document).ready(function() {    
  $('tr.parent').click(function(){
    $(this).siblings('.child-' + this.id).toggle();
    return false;
  });
});
</script>

The problem now, is that the window scrolls always to the top after a table row is clicked. I want it to stay at the scrolling position that it was before the click.

The child rows get collapsed as supposed to, but the document scrolls to the top immediately after the click, even though i have returned false at the end of .click... What am I doing wrong?

4

2 回答 2

0

即使您没有在点击处理程序中返回 false,页面也不应该滚动以响应点击。

页面是否足够短,以至于当某些行折叠时,页面变得足够短以使其全部适合视口?(因此浏览器自然会向上滚动以填充视口。)

更新scrollTop如果是这种情况,您可能会考虑在通话期间尝试保留:

$(document).ready(function() {    
  $('tr.parent').click(function(){
    var scrollTop = document.body.scrollTop;        // <== Save the current value
    // *** Maybe append something to the page here to keep it tall***
    $(this).siblings('.child-' + this.id).toggle();
    // *** Maybe remove the appended thing now ***
    document.body.scrollTop = scrollTop;            // <== Restore it
    return false;
  });
});

如果所有这些都在 以外的容器中body,您可能需要尝试将其保存在该容器中,但您明白了。根据页面高度的变化程度,这可能并不完美,但它可能会有所帮助。

于 2010-10-30T09:18:59.200 回答
0

好的,所以我尝试了 TJ 的建议来解决问题。

我改成var scrollTop = document.body.scrollTopvar scrollTop = window.pageYOffset因为不知何故document.body.scrollTop总是返回 0(不知道为什么)。为pageYOffset我返回正确的滚动位置。顺便说一句,我在 Firefox 中完成了所有这些操作。

我最终得到了这段代码:

  <div id="bottomspacer" style="height: 1000px; display: none; "></div>
  <script type="text/javascript">
  $('tr.parent').click(function(){
    $('#bottomspacer').show();
    var scrollTop = window.pageYOffset;
    $(this).siblings('.child-' + this.id).toggle();
    document.body.scrollTop = scrollTop;
    $('#bottomspacer').hide();
    return false;
  });
  </script>
于 2010-10-31T08:46:17.353 回答