我正在使用 javascript 來修改頁面的樣式,并且效果很好。然而,下一步是更改表格第一列的樣式。如何僅識別和設定第一列的樣式?到目前為止,我的其他更改是基于 ID 或基于具有類的許多專案。在這個例子中,我只知道它們是 TH 或 TD 元素,我想更改第一列中的元素。
萬一有人問,這是我到目前為止的代碼......這是有效的,并且與設定第一列的樣式沒有任何關系
function rotate_headers() {
const collection = document.getElementsByTagName("th");
for (let i = 0; i < collection.length; i )
{
collection[i].innerHTML =
'<div style="padding-left: 100%;"><div style="transform: translate(7px, 3px) rotate(315deg); width: 30px;"><span style="border-bottom: 1px solid #ccc; padding: 5px 10px; color:grey;"' collection[i].innerHTML '</span> </div></div>';
// collection[i].style.background = "#6877c3"; //
//collection[i].style.height = "100px"; //
}
const collection2 = document.getElementsByClassName("table-bordered");
for (let i = 0; i < collection2.length; i )
{ collection2[i].style.border = "0px";
collection2[i].style.marginTop = "95px";
}
const collection3 = document.getElementsByClassName("highlight");
for (let i = 0; i < collection3.length; i )
{ collection3[i].classList.remove("highlight"); }
const collection4 = document.getElementsByClassName("table-content");
for (let i = 0; i < collection4.length; i )
{ collection4[i].style.padding = "1rem 1rem"; }
const collection5 = document.getElementsByClassName("table-content");
for (let i = 0; i < collection5.length; i )
{ collection5[i].style.width = "100px";
collection5[i].style.position = "relative";
collection5[i].style.whiteSpace = "nowrap";
collection5[i].style.overflowX = "scroll";
collection5[i].style.overflowY = "hidden";
}
}
下面的代碼做我想要的,但前提是我的表有一個 ID ......我的通常沒有。
var table = document.getElementById('test');
for (var i = 1; i < table.rows.length; i ) {
var firstCol = table.rows[i].cells[0]; //first column
firstCol.style.background = 'red'; // or anything you want to do with first col
}
下面的代碼不起作用......這是我的問題
var table = document.getElementsByTagName("table");
for (var i = 1; i < table.rows.length; i ) {
var firstCol = table.rows[i].cells[0]; //first column
firstCol.style.background = 'red'; // or anything you want to do with first col
}
uj5u.com熱心網友回復:
您可以使用document.querySelectorAll('tr th:first-child, tr td:first-child')然后迭代結果設定您想要的樣式。
let firstCol = document.querySelectorAll('tr th:first-child, tr td:first-child')
for (let i = 0; i < firstCol.length; i ) {
firstCol[i].style.color = 'red'
}
<table>
<tr>
<th>one</th>
<th>two</th>
<th>three</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</table>
uj5u.com熱心網友回復:
我想你會在下一篇文章中找到答案: https ://developer.mozilla.org/en-US/docs/Learn/HTML/Tables/Basics
在繼續之前,我們將在本文中向您介紹最后一個功能。HTML 有一種方法可以在一個地方定義一整列資料的樣式資訊 - 和元素。這些存在是因為在列上指定樣式可能有點煩人且效率低下——您通常必須在每個列或列中指定樣式資訊,或者使用復雜的選擇器,例如 :nth-child。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/479010.html
標籤:javascript css
