2014-10-31 149 views
1

我有一個jQuery函數表上空盤旋行/列,您可以在這裏看到:http://jsfiddle.net/v0r9kjq7/這是代碼:將鼠標懸停在表列,行和標題列

HTML:

<table> 
<thead> 
    <tr> 
     <th>Title 1</th> 
     <th>Title 2</th> 
     <th>Title 1</th> 
     <th>Title 2</th> 
    </tr> 
</thead> 
<tbody> 
    <tr> 
     <td>Content here</td> 
     <td>Content here</td> 
     <td>Content here</td> 
     <td>Content here</td> 
    </tr> 
    <tr> 
     <td>Content here</td> 
     <td>Content here</td> 
     <td>Content here</td> 
     <td>Content here</td> 
    </tr> 
    <tr> 
     <td>Content here</td> 
     <td>Content here</td> 
     <td>Content here</td> 
     <td>Content here</td> 
    </tr> 
    <tr> 
     <td>Content here</td> 
     <td>Content here</td> 
     <td>Content here</td> 
     <td>Content here</td> 
    </tr> 
    <tr> 
     <td>Content here</td> 
     <td>Content here</td> 
     <td>Content here</td> 
     <td>Content here</td> 
    </tr> 
    <tr> 
     <td>Content here</td> 
     <td>Content here</td> 
     <td>Content here</td> 
     <td>Content here</td> 
    </tr> 
</tbody> 
</table> 

CSS:

table { 
width: 100%; 
border-spacing: 0; 
vertical-align: top; 
table-layout: auto; 
} 
table tr.hover td { 
cursor: pointer; 
background-color: rgba(30, 138, 228, 0.15); 
} 
table td { 
padding: 0 10px; 
line-height: 30px; 
background-color: inherit; 
color: #3c3c3c; 
} 
tr:nth-child(even) { 
background-color: #f0f0f0; 
} 
tr:nth-child(odd) { 
background-color:#fff; 
} 
tbody tr:hover, tbody td.hover { 
background-color: rgba(30, 138, 228, 0.15) !important; 
} 
td:hover { 
background-color: #fff !important; 
color: #1e8ae4; 
cursor: pointer; 
} 
tbody td.hover:hover { 
background-color: #fff !important; 
} 
table thead th { 
background-color: #f0f0f0 !important; 
} 
table thead th { 
padding: 20px 10px 20px 10px; 
font-weight: bold; 
color: #3c3c3c; 
vertical-align: top; 
text-align: left; 
} 

JQUERY:

$('table td').hover(

function() { 
$('table td:nth-child(' + ($(this).index() + 1) + ')').addClass('hover'); 
}, 

function() { 
$('table td:nth-child(' + ($(this).index() + 1) + ')').removeClass('hover'); 
}); 

我應該如何改變這個腳本,這樣它也會考慮到表頭,所以標題列也會被徘徊?

非常感謝所有幫助!

回答

4

你只需要更新的選擇,包括th元素以及:

$('table td, table th').hover(function() { 
    // rest of your code... 
}); 

Updated fiddle

2

我錯過了懸停類的例子

.hover { 
    background-color: #fff !important; 
    color: #1e8ae4; 
    cursor: pointer; 
} 

然後,它的工作原理,如果你做

$('table td').hover(function() { 
    $('table td:nth-child(' + ($(this).index() + 1) + ')').addClass('hover'); 
    $('table th:nth-child(' + ($(this).index() + 1) + ')').addClass('hover'); 
}, function() { 
    $('table td:nth-child(' + ($(this).index() + 1) + ')').removeClass('hover'); 
    $('table th').removeClass('hover'); 
});