2015-05-26 95 views
7

我跟在@ koala_dev的代碼this post嘗試鎖定第一列,我的表水平滾動。不幸的是,代碼對我的表沒有影響。我想知道是否有人可以給我一些關於我做錯了什麼的指示,因爲我是編程新手。修復引導表的第一列

這是我的表: http://jsfiddle.net/mademoiselletse/bypbqboe/59/

這是我在JS插入的代碼(行121-133):

$(function() { 
    var $tableClass = $('.table'); 
    // Make a clone of our table 
    var $fixedColumn = $tableClass.clone().insertBefore($tableClass).addClass('fixed-column'); 

    // Remove everything except for first column 
    $fixedColumn.find('th:not(:first-child),td:not(:first-child)').remove(); 

    // Match the height of the rows to that of the original table's 
    $fixedColumn.find('tr').each(function(i, elem) { 
     $(this).height($tableClass.find('tr:eq(' + i + ')').height()); 
    }); 
}); 

這是CSS屬性(線36-47)我有插入:

.table-responsive > .fixed-column { 
    position: absolute; 
    display: inline-block; 
    width: auto; 
    border-right: 1px solid #ddd; 
} 

@media(min-width:768px) { 
    .table-responsive>.fixed-column { 
     display: none; 
    } 
} 

我從demo code偏離的唯一的事情是,我定義爲$('.table')$tableClass而不是$table,因爲我之前已將var $table定義爲$('#table')。您的幫助將非常感謝!

+0

在您的演示有這$ var'$ tableClass = $('。table');'即你試圖讓你的表對象引用類,但是你已經把'table'作爲'table'而不是'classN ame'作爲'表' –

+0

感謝您指出!我通過ID引用表,但我得到這個: http://jsfiddle.net/mademoiselletse/bypbqboe/62/ 你能給我一些提示,爲什麼這是什麼? – Vic

+0

你的代碼很混亂!你爲什麼要克隆'table',爲什麼要除去第一個表中的所有'table data'和'table head'? –

回答

27

確定..刪除所有js代碼,你可以用一些CSS技巧如下做到這一點:

DEMO

CSS

.table > thead:first-child > tr:first-child > th:first-child { 
    position: absolute; 
    display: inline-block; 
    background-color: red; 
    height: 100%; 
} 

.table > tbody > tr > td:first-child { 
    position: absolute; 
    display: inline-block; 
    background-color: red; 
    height: 100%; 
} 

.table > thead:first-child > tr:first-child > th:nth-child(2) { 
    padding-left: 40px; 
} 

.table > tbody > tr > td:nth-child(2) { 
    padding-left: 50px !important; 
} 
+1

太棒了!非常感謝! – Vic

+0

隨時! Happy Coding .. :) –

+1

這是一個非常好的純CSS解決方案,它從其他引用的帖子中擺脫了JS&CSS混亂的垃圾。 – wndxlori

1

$('#table')表示您的查找元素編號爲table

$('.table')意味着你的尋找元素按類table

這些是您在CSS中使用的CSS選擇器。

對於您的情況,您的表的編號爲table,因此您可以使用$('#table')選擇該表。

而且您沒有任何使用類table的html元素,因此當您選擇使用$('.table')時,您將不會收到任何內容。

+0

感謝您指出我沒有'table'類。我意識到我把'table'放在'data-class'裏面。我遵循你的建議,並通過它的ID引用表,但我得到了這個: http://jsfiddle.net/mademoiselletse/bypbqboe/62/ 我的代碼是否有衝突? – Vic