2010-09-17 91 views
2

里面我得到了以下HTML:跳转到内容可滚动的div

<div style="height:200px;overflow-y:scroll;"> 
    <table>.....</table> 
</div> 

在此设置下,我有点模仿扩大<select>控制与定义@size属性。所以,用户可以选择表中的一行。有没有办法让表格“跳起来”,以便选定的行显示在div的顶部,垂直滚动条滚动到其位置。我不需要实际的滚动效果。表格应该在行点击时立即改变它的位置。

+0

所以你想这个http://www.balupton.com/sandbox/jquery-scrollto/demo/没有文档滚动? – balupton 2010-09-17 18:51:29

+0

@balupton - 几乎是。非常相似。我要花点时间检查一下。谢谢。 – Dimskiy 2010-09-17 19:05:54

回答

2

这可能会实现:

$("#scrollableDiv").animate({ 
    scrollTop: 200 // scrolls to the bottom 
}, 1000); 
+0

请参阅http://www.learningjquery.com/2007/09/animated-scrolling-with-jquery-12 – elektronikLexikon 2010-09-17 18:52:11

+0

@elektronikLexikon:这看起来工作得最好。我怎样才能找出它应该滚动的魔术像素数量?表格行高度不均匀。我正在考虑为点击之前的每一行计算行高。有更容易的方法吗? – Dimskiy 2010-09-17 19:30:43

+0

尝试抵消方法: $(“tr#blah_blah_blah”)。offset()。top – elektronikLexikon 2010-09-17 19:33:37

1

我建议使用scrollTop的(或者即使你想制作动画)。 http://www.balupton.com/sandbox/jquery-scrollto/demo/

做你想做什么:

  // Fetch the scrollable div 
      $container = $('#scrollable'); 
      // Fetch the target div 
      $target = $('#target'); 

      // Prepare the Inline Element of the Container 
      var $inline = $('<span/>').css({ 
       'position': 'absolute', 
       'top': '0px', 
       'left': '0px' 
      }); 
      var position = $container.css('position'); 

      // Insert the Inline Element of the Container 
      $container.css('position','relative'); 
      $inline.appendTo($container); 

      // Determine the Offsets 
      var startOffset = $inline.offset().top, 
       targetOffset = $target.offset().top, 
       offsetDifference = targetOffset - startOffset; 

      // Perform the jump 
      $container.css('scrollTop',offsetDifference+'px') 

我们在这里添加一个内联,以确保我们

$('div')[0].scrollTop = 200 //would set the scrollable div to 200px down. 

http://jsfiddle.net/8mepH/

1

这里被使用的代码的修改提取物在可滚动区域内获取正确的开始位置。我们使用偏移差异,所以如果你想做动画,它从起始位置动画,而不是跳到其他地方。