2010-08-03 111 views
1

好吧,這基本上是關於可滾動表格。如何在Google Chrome中創建可滾動表格

如果我有一個表格元素,我可以通過設置固定高度和固定高度來使內容可滾動(帶有一些javascript樂趣,包括使用寬度的滾動條的計費),然後將滾動設置爲自動在tbody上。

這適用於Firefox,但在谷歌瀏覽器中,thead/tbody的高度被忽略,並且整個表的增長與預期的滾動相比。

是否有一個可以應用到表中的CSS解決方案,以使這項工作在谷歌瀏覽器以及?或者,我是否需要將標題放在一張表中,正文是不同的表格,使用js或css確保列寬,並讓正文表格的父項隨其內容一起滾動?

+0

這將是可怕的非語義標記。你有沒有嘗試設置整個桌子的高度? – MvanGeest 2010-08-03 17:30:48

+1

你可以發表一些代碼嗎? – cesarnicola 2010-08-03 18:11:29

+0

桌子上的高度充當最小高度屬性。不能強制桌子只有一定的高度。我想要一個解決方案,不需要我把表格分成兩個表格,一個用於設置列寬的第一個表格。 – 2010-08-05 19:56:59

回答

1

這是一個應該工作的完整解決方案(使用jQuery) 您需要在單獨的div元素中各有兩個表。每個表格將具有相同的thead部分。只有contentTable將有TBODY部分

<div class="scrollableTable" 
    <div> 
     <table class="headerTable"> 
      <thead> 
       <tr> 
        <th>Column 1</th> 
        <th>Column 2</th> 
        <th>Column 3</th> 
       </tr> 
      </thead> 
     </table> 
    </div> 
    <div style="height:240px; overflow:auto;"> 
     <table class="contentTable" style="width:100%; margin-top:-20px;"> 
      <thead> 
       <tr> 
        <th>Column 1</th> 
        <th>Column 2</th> 
        <th>Column 3</th> 
       </tr> 
      </thead> 
      <tbody> 
       <tr> 
        <td>value 1</td> 
        <td>value 2</td> 
        <td>value 3</td> 
       </tr> 
       <tr> 
        <td>value 4</td> 
        <td>value 5</td> 
        <td>value 6</td> 
       </tr> 
       .... 
      </tbody> 
     </table> 
    </div> 
</div> 

然後,你將有每一個數據改變時調用這個函數:

ResizeWidths($('.scrollableTable')); 


function ResizeWidths(div) 
{ 
    var headerCells = $(div).find('.headerTable thead').find('th'); 
    var contentCells = $(div).find('.contentTable thead').find('th'); 
    for(var i =0, ii = headerCells.length;i<ii;i++) 
    { 
     if($(headerCells[i]).width()!=$(contentCells[i]).width()) 
      $(headerCells[i]).width($(contentCells[i]).width()); 
    } 
} 
+0

我想要一個單一表格的解決方案,它可以在除chrome之外的所有瀏覽器上工作,我只是想了解爲什麼chrome不能正常工作。 – 2010-08-05 21:03:41

+0

我希望避免這樣的事情,但看起來我可能別無選擇,只能這樣做。 – 2010-08-24 20:56:19

+0

我已經在IE7/8,Chrome和FF上測試過,效果很好。我添加了兩件事:1)'$(div).find('。contentTable')[0] .style ['marginTop'] = ' - '+ $(contentCells [0])。height()+ 'px';'動態分配負邊界。 2)代碼來同步頭和內容div之間的水平滾動。在FF和Chrome中,我使用了onscroll事件。在IE 7/8中,我添加了一個100ms的setInterval調用同步方法(我知道,醜陋,但工程)。 – helios 2012-01-17 12:18:05

1

我猜你是使用腳本從以下page

爲了解決在Chrome中發生的錯誤,請更改以下行:

if (document.all && document.getElementById && !window.opera) this.initIEengine(); 
    if (!document.all && document.getElementById && !window.opera) this.initFFengine(); 

這樣:

var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1; 
    if (is_chrome = true) { 
     this.initIEengine() 
    } 
    else { 
     if (document.all && document.getElementById && !window.opera) this.initIEengine(); 
     if (!document.all && document.getElementById && !window.opera) this.initFFengine(); 
    } 

完美的作品,然後

+0

不使用該腳本...但是這是一個全局的事情,將在整個頁面中設置一些IE行爲?這感覺更接近於使用核武器來殺死一隻老鼠。仍然很高興知道有什麼可以做的。 – 2011-01-15 15:00:34