2010-09-17 93 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

這裏被使用的代碼的修改提取物在可滾動區域內獲取正確的開始位置。我們使用偏移差異,所以如果你想做動畫,它從起始位置動畫,而不是跳到其他地方。