簡體   English   中英

如何在每個單元格中使用唯一顏色突出顯示on表格單元格

[英]how to highlight a table cell onClick with unique colors in each cell

在下面的小提琴中,您可以單擊任何單元格,它們會將顏色更改為CSS中td.highlighted中的顏色。 我希望突出顯示的顏色可以內聯分配,並且每個元素都是唯一的。

https://jsfiddle.net/rvxnmz8r/7

這是為每個表元素生成樣式的行,我認為主要的問題是我對CSS很愚蠢。 謝謝你的幫助。

var hstyle = 'style="td.highlighted {background-color: ' + '#'+Math.random().toString(16).substr(-6)  + '; color: black;}"';

更新:單元格需要在默認顏色和自定義突出顯示顏色之間保持切換狀態。

當使用內聯樣式與外部CSS結合使用時,外部需要!important是覆蓋內聯樣式。

作為旁注,使用!important影響樣式的可用性以更難以重用的方式,但在您的情況下,創建60個類來切換,我發現更糟糕,因此使用!important

將腳本更改為

var hstyle = 'style="background-color: ' + '#' + Math.random().toString(16).substr(-6) + '; color: black;"';`

而你的CSS

td.highlighted {
  background-color: blue !important;
  color: white !important;
}

堆棧代碼段

 var elements = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; var transtable = [elements, elements, elements, elements, elements, elements]; var output = []; output.push('<table id="taxatable">'); for (var row = 0; row < transtable[0].length; row++) { output.push('<tr>'); for (var col = 0; col < transtable.length; col++) { var hclass = 'class="highlighted"'; var hstyle = 'style="background-color: ' + '#' + Math.random().toString(16).substr(-6) + '; color: black;"'; output.push( '<td ' + hclass + ' ' + hstyle + '>' + escape(transtable[col][row]) + '</td>' ); } output.push('</tr>'); } output.push('</table>'); document.getElementById('output').innerHTML = output.join(''); var tbl = document.getElementById("taxatable"); if (tbl != null) { for (var trow = 0; trow < tbl.rows.length; trow++) { for (var tcol = 0; tcol < tbl.rows[trow].cells.length; tcol++) { tbl.rows[trow].cells[tcol].onclick = function() { this.classList.toggle("highlighted"); }; //console.log(tbl.rows[trow].cells[tcol]); } } } 
 td { background-color: black; color: white; } td.highlighted { background-color: blue !important; color: white !important; } 
 <div id="output"> </div> 

編輯

我看到你正在嘗試做什么,但你的解決方案是將兩個東西混合在一起:內聯樣式和CSS規則。 您只能在元素上使用style=""直接在該元素上設置樣式,這將覆蓋樣式表中的規則。 如果你想打開和關閉highlight類,你可以做這樣的事情(使用jQuery):

$("td").click(function() {
    $(this).toggleClass('highlighted');
});

此外,它需要highlighted類中的!important修飾符,如上面的@LGSon所述。

結合我在下面的回答(刪除內聯樣式中的td.highlighted ),這可能會導致您正在尋找的內容。


老答案

如果使用內聯樣式,則直接在HTML元素上設置樣式,您不需要定義CSS選擇器。 代替

var hstyle = 'style="td.highlighted {background-color...

你可以簡單地寫:

var hstyle = 'background-color...'

所以,你的代碼變成:

var hstyle = 'style="background-color: ' + '#'+Math.random().toString(16).substr(-6)  + '; color: black;"';

你很親密 像這樣刪除td.highlighted

var hstyle = 'style="background-color: ' + '#'+Math.random().toString(16).substr(-6)  + '; color: black;"';

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM