2015-02-08 63 views
0

我想做與「Scroll to」相反的操作:即,不是滾動到div,而是希望div滾動到我。 「我」是以下行的一個(Twitter的引導row):JQuery:將元素滾動到視口

+-------------+-----------+ +-------------+-----------+ 
+-------------+   | +-------------+   | 
+---click-----+ div  | +-------------+   | 
+-------------+   | +-------------+   | 
+-------------+   | +-------------+   | 
+-------------+-----------+ +-------------+   | 
+-------------+   | +-------------+   | 
+-------------+   | +-------------+   | 
+-------------+   | +-------------+   | 
+-------------+   | +-------------+   | 
+-------------+   | +-------------+   | 
+-------------+   | +-------------+-----------+ 
+-------------+   | +-------------+   | 
+-------------+   | +---click-----+ div | 
+-------------+   | +-------------+   | 
+-------------+   | +-------------+   | 
+-------------+-----------+ +-------------+-----------+ 

見,當我點擊左下角行,視滾動到內容DIV之一。我想要相反的:我想要這個div(在飛行中創建一個twitter引導col-nn,而不是可以語義上「滑動」在自己的高容器內)滾動到位。

因此,row將不得不點擊,以某種方式檢測到div是看不見的。這可能是seems;但移動div部分呢?

<div class="row"> 
    <div class="col col-lg-12 col-sm-12"> 
    <div class="col-md-8"> 
     <table class="table"> 
     <thead> 
      <tr> 
      <th>Row title</th> 
      </tr> 
     </thead> 
     <tbody> 

      <tr class="my_row"> 
      <td>row</td> 
      </tr> 

      <tr class="my_row"> 
      <td>row</td> 
      </tr> 

      <tr class="my_row"> 
      <td>row</td> 
      </tr> 

      <tr class="my_row"> 
      <td>row</td> 
      </tr> 

      <tr class="my_row"> 
      <td>row</td> 
      </tr> 
<!-- a lot of other rows -->   
     </tbody> 
     </table> 
    </div> <!-- col-md-8 --> 

    <div id="details" class="col-md-4 details"> 
     <div>THIS IS THE DIV</div> 
    </div> <!-- col-md-4 --> 

    </div> <!-- col-sm-12 --> 
</div> 
+2

可以發佈'html','js'? – guest271314 2015-02-08 22:30:16

+0

爲什麼downvote? – yPhil 2015-02-08 22:39:28

+0

我沒有downvote,但我確實讀過你的問題5次,仍然不明白你想要做什麼,所以這可能是一個原因。 – wojtow 2015-02-08 23:02:10

回答

4

我寫這個jsFiddle說明你怎麼可能做到像你說什麼,那就是如果我理解你想要正確的。我使用了CSS3轉換來實現實際的動畫,由於在更改DIV的「top」屬性時發生了0ms超時,所以會觸發實際的動畫。在我提供的示例中,我將DIV的頂部對齊到被點擊的行的頂部。顯然,如果你願意,你可以改變它在中心浮動(通過做一些數學運算)。

希望它指出你在正確的方向!

HTML

正如你的問題提供...

CSS

#details { 
    transition: top 0.2s ease-in-out; 
} 

的JavaScript

$(document).ready(function() { 
    $("#details").css("top", $(".my_row:first").offset().top); 
    $(".my_row").click(function() { 
     var row = $(this); 
     setTimeout(function() { 
      $("#details").css("top", row.offset().top); 
     }, 0); 
    }); 
}); 
+1

這是純粹的天才。您不僅瞭解我的問題,而且還提供了一個簡單而優雅的解決方案。主席先生,你是一位紳士和學者。 – yPhil 2015-02-09 20:15:58

+0

'row.offset()。top''更好的工作'offset()'。這真的很酷。 – yPhil 2015-02-09 21:18:46

+1

很高興我能幫忙! – FarligOpptreden 2015-02-10 05:22:46