如何在动态创建的表中添加“样式”?

时间:2013-12-28 07:51:48

标签: javascript

我已经通过DOM创建了表,现在想要为该表添加样式但它不起作用。 代码:

<script>
    var nrCols=4;
    var maxRows=10;
    var nrRows=maxRows+1;
    while(nrRows>maxRows)
    {
        nrRows=Number(prompt('How many rows? Maximum '+maxRows+' allowed.',''));
    }
    var root=document.getElementById('mydiv');
    var tab=document.createElement('table');
    var style=document.createElement('style');
    style.setAttribute('background-color','red');
    tab.appendChild(style);

    tab.setAttribute('Border','1');

    tab.className="mytable";
    var tbo=document.createElement('tbody');

    var tr1= document.createElement('tr');
    var th1= document.createElement('th');
    th1.appendChild(document.createTextNode('No.'));

    var th2= document.createElement('th');
    th2.appendChild(document.createTextNode('Surah.'));

    tr1.appendChild(th1);
    tr1.appendChild(th2);
    tbo.appendChild(tr1);

    var row, cell;
    for(var i=0;i<nrRows;i++){
        row=document.createElement('tr');
        for(var j=0;j<nrCols;j++){
            cell=document.createElement('td');
            cell.appendChild(document.createTextNode('Allah'+' '+j))
            row.appendChild(cell);
        }
        tbo.appendChild(row);
    }
    tab.appendChild(tbo);
    root.appendChild(tab);
</script>

我使用了style.setAttribute('background-color','red');,但没有区别。如何解决?

4 个答案:

答案 0 :(得分:2)

替换

var style=document.createElement('style');
    style.setAttribute('background-color','red');
    tab.appendChild(style);

with:

tab.style.backgroundColor = 'red';

所有元素都有一个样式属性,您可以在其中添加适当的样式值。

答案 1 :(得分:1)

尝试更改可能导致css样式混乱的var样式的名称,尝试这种方式

var menu = document.createElement("menu");
menu.style.backgroundColor = "#555";

答案 2 :(得分:0)

嗯,style是一个HTML标记,当你创建一个具有该名称的元素时,它需要CSS信息。你可能想要这个:

如果你想定位<th>元素,你应该使用它:

var th1 = document.createElement('th');
th1.style.backgroundColor = 'red';

Demo

答案 3 :(得分:-1)

它应该是这样的

 document.body.style.backgroundColor="#333333";

在你的情况下

 tab.style.backgroundColor="#333333"

下面的代码将创建样式标记

 var css = 'table { background: red; }'
 var style = document.createElement('style');
 style.styleSheet.cssText = css;
相关问题