我有一个向自动生成的文本节点添加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);
}
有人能帮助我吗?非常感谢。
可能的重复 - > http://stackoverflow.com/questions/524696/how-to-create-a-style-tag-with-javascript – ManseUK 2012-01-05 16:39:35