【问题标题】:Switching cell background color of a table created with javascript切换使用 javascript 创建的表格的单元格背景颜色
【发布时间】:2011-08-27 20:54:35
【问题描述】:

我有一个问题: 我需要一个 7x48 单元格的表格,这些单元格具有背景颜色(灰色),单击时必须可切换(绿色),然后再次单击即可再次切换。 我使用以下 js 函数创建了表:

function createGrid(){
// get the reference for the body
    var grid = document.getElementById("grid");
    var green="#33CC66";
    var grey="#DEDEDE";

    // creates a <table> element and a <tbody> element
    var tbl     = document.createElement("table");
    var tblBody = document.createElement("tbody");
    tbl.id="timegrid";
    tbl.style.backgroundColor=grey;
    // creating all cells
    for (var j = 0; j < 7; j++) {
        // creates a table row
        var row = document.createElement("tr");

        for (var i = 0; i < 48; i++) {
            // Create a <td> element and a text node, make the text
            // node the contents of the <td>, and put the <td> at
            // the end of the table row
            var cell = document.createElement("td");

            cell.onmousedown=function(){
                if(this.style.backgroundColor!=grey)
                this.style.backgroundColor=grey;
                else this.style.backgroundColor=green;                  

            };
            row.appendChild(cell);
        }

        // add the row to the end of the table body
        tblBody.appendChild(row);
    }

    // put the <tbody> in the <table>
    tbl.appendChild(tblBody);
    // appends <table> into <div id="grid">
    grid.appendChild(tbl);
    tbl.setAttribute("cellPadding", "7");
    tbl.setAttribute("cellSpacing", "0");
    tbl.setAttribute("border", "1");}

问题是:它第一次工作(从灰色单元格切换到绿色)但我第二次单击同一个单元格时无法返回原始颜色。 有什么建议吗?

【问题讨论】:

    标签: javascript html-table cell background-color


    【解决方案1】:

    问题是浏览器没有保留您设置的相同值。

    例如,如果你这样做

    document.body.style.backgroundColor = '#33cc66'
    console.log(document.body.style.backgroundColor);
    

    您会收到 rgb(51, 204, 102) 返回。 (让大家知道 StackOverflow 是可怕的绿色背景。)

    此值为functional notation for colour

    您可能需要存储您设置的值,因为浏览器报告当前颜色值的方式不一致。

    cell.onmousedown=function(){
        if(background !== grey) {
            this.style.backgroundColor=grey;
            background = grey;
        } else {
            this.style.backgroundColor=green;      
            background = green;            
        }
    };
    

    【讨论】:

    • 感谢您的回答,但我只是使用类名解决了问题,而不是在 js 中声明单元格的样式: if(this.className=="greenCell") this.className="greyCell";否则 this.className="greenCell";
    • @breathe0 没问题。如果答案解决了您的问题,您可以mark it as accepted
    猜你喜欢
    • 2012-07-16
    • 2020-07-08
    • 2016-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多