[英]Pure Javascript table column hover effect?
這是一種基於列的方法。 當鼠標進入/離開一個單元格時,通過索引找到相應的<col/>
並應用/刪除所需的類:
(() => { const myTable = document.getElementById("myTable"); const cols = myTable.querySelectorAll("col"); const events = { mouseover: e => { const t = e.target.closest("td"); if (t) { const cellIndex = t.cellIndex; for (let i = 0, n = cols.length; i < n; i++) { cols[i].classList[i === cellIndex ? "add" : "remove"]("hovered"); } } }, mouseout: e => { const t = e.target; if (t.nodeName === "TD" && !t.contains(e.relatedTarget)) { cols[t.cellIndex].classList.remove("hovered"); } } }; for (let event in events) { myTable.addEventListener(event, events[event]); } })();
.hovered { background-color: #FF0000; }
<table id="myTable" cellspacing="0"> <col /> <col /> <col /> <tbody> <tr> <td>Col1</td> <td>Col2</td> <td>Col3</td> </tr> <tr> <td>Col1</td> <td>Col2 <span>nested</span> </td> <td>Col3</td> </tr> <tr> <td>Col1</td> <td>Col2</td> <td>Col3</td> </tr> </tbody> </table>
也可以看看:
Element. classList
Node. Contains()
Element. Closest()
這是您的代碼(+ 演示 ):
var HOVER_CLASS = 'hovered';
var hovered;
table.addEventListener('mouseover', function (e) {
if (e.target.tagName.toLowerCase() == 'td') {
var index = e.target.cellIndex;
hovered && hovered.forEach(function (cell) {
cell.classList.remove(HOVER_CLASS);
});
hovered = Array.prototype.map.call(
table.rows,
function (row) {
var i = index;
while (!cell && i >= 0) {
var cell = row.cells[i];
i -= 1;
}
return cell;
}
);
hovered.forEach(function (cell) {
cell.classList.add(HOVER_CLASS);
});
}
}, true);
table.addEventListener('mouseout', function (e) {
hovered && hovered.forEach(function (cell) {
cell.classList.remove(HOVER_CLASS);
});
hovered = null;
}, true);
我能想到的最好的方法是給每個<td>
一個類名,以標識它所在的列。即“ col1,col2等”
然后,您可以使用document.getElementsByClassName("colX")
函數獲取這些<td>
的數組,遍歷該數組並修改樣式。 警告,這可能在沒有getElementsByClassName函數的較舊的瀏覽器中不起作用,但是有一些變通辦法可以輕松找到。 最好的辦法是使用jQuery,但不確定為什么要反對它。
您在CSS中創建一個類
.HoverTabla > tbody > tr:hover,
.HoverTabla > tbody > tr:focus {
background-color: #42C6F7;
}
然后從html的表格中調用它
<table class="table HoverTabla" id="tbl_Plan">
<thead>
<tr>
<th>Tipo de plan</th>
<th>Tiempo en días</th>
<th>Max. Usuario</th>
<th>Max. Capacidad</th>
<th>Max. Casos</th>
<th>Valor plan</th>
<th></th>
</tr>
</thead>
</table>
我經過一番谷歌搜索后發現了純CSS答案: https : //css-tricks.com/simple-css-row-column-highlighting/
表中的每個單元格( <td>
)都通過偽元素進行了填充,用於創建懸停效果。 為了確保懸停效果不會超出表本身,請使用overflow: hidden
。
本文中的小標題概括了這一切:“訣竅是在<td>
上使用巨大的偽元素,隱藏在表溢出中”
嘗試
<td onMouseOver="this.bgColor='yellow';" onMouseOut="this.bgColor='white';">
這將起作用,不需要使用javascript。 因此,即使人們關閉了javascript,它也應該起作用。
Jfiddle: http : //jsfiddle.net/vJacZ/
HTML:
<table>
<tr>
<td class="column1">
Column1
</td>
<td class="column2">
Column2
</td>
</tr>
</table>
CSS:
.column1{
color:black;
}
.column1:hover{
color:red;
}
.column2{
color:black;
}
.column2:hover{
color:green;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.