2012-01-05 222 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