2012-01-05 53 views
1

我有一个向自动生成的文本节点添加CSS样式的问题。我知道textnode没有任何父节点。所以我不能在其中添加CSS样式。动态添加CSS样式到文本节点

基本上,我需要做的是,当用户点击“+”按钮,我在页面中创建它,它会添加一个新的文本节点。当用户再次单击时,它会不断添加另一个新的文本节点。不过,我想在textnode创建后添加一个css样式。

这里是我的代码:

function addRowToTable() { 

//find the last row in the table and add the new textnode when user clicks on the button 
var tbl = document.getElementById('audioTable2'); 
var lastRow = tbl.rows.length; 
var iteration = lastRow; 
var row = tbl.insertRow(lastRow); 

//after find the last row in the table, and it will add the new cell with the new textnode 
    var cellLeft = row.insertCell(0); 
    var el_span = document.createElement('span'); 
    var el_spanClass = el_span.setAttribute('class', 'test'); 
    var textNode = document.createTextNode(iteration); 
    cellLeft.appendChild(textNode); 
} 

//this is the css style I would like to apply into the new gerenated textnode 
function appendStyle(styles){ 
    var css = document.createElement('style'); 
css.type='text/css'; 

if (css.styleSheet) css.styleSheet.cssText = styles; 
else css.appendChild(document.createTextNode(styles)); 
document.getElementsByTagName("head")[0].appendChild(css); 
} 

有人能帮助我吗?非常感谢。

+0

可能的重复 - > http://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript – ManseUK 2012-01-05 16:39:35

回答

3

你说:“我在加入CSS样式到产生textnode汽车的问题,” ,但你的代码提供表明你正在尝试一个style元素添加到head为每新的textnode。我想你想要的是1)将样式表中已定义的样式应用于textnode,或者2)直接设置textnode的内联样式。因此,我认为你的代码应该是:

1)通过span应用样式在你的CSS样式表的textnode:

//after find the last row in the table, and it will add the new cell with the new textnode 
    var cellLeft = row.insertCell(0); 
    var el_span = document.createElement('span'); 
    var el_spanClass = el_span.setAttribute('class', 'test'); 
    var textNode = document.createTextNode(iteration); 
    cellLeft.appendChild(el_span); 
    el_span.appendChild(textNode); 
} 

这使span进入细胞(你不在你的代码中执行),然后将该文本节点用跨度给出classtest

2)通过span直接(在线)应用样式到textnode:

//after find the last row in the table, and it will add the new cell with the new textnode 
    var cellLeft = row.insertCell(0); 
    var el_span = document.createElement('span'); 
    el_span.setAttribute('style', 'color: red'); /*just an example, your styles set here*/ 
    var textNode = document.createTextNode(iteration); 
    cellLeft.appendChild(el_span); 
    el_span.appendChild(textNode); 
} 

在这两种情况下,你的appendStyle功能可以删除。

+0

Everyting正在工作。非常感谢。两种方法都是有效的。 – 2012-01-05 20:59:31

相关问题