2012-01-05 19 views
1

自動生成されたtextnodeにCSSスタイルを追加する問題があります。私はtextnodeに親ノードがないことを知っています。だから私はちょうどそれにCSSのスタイルを追加することはできません。テキストノードにCSSNスタイルを動的に追加する

基本的に、私がする必要があるのは、ユーザーがページで作成した「+」ボタンをクリックして、新しいテキストノードをページの1つに追加するときです。ユーザーがもう一度クリックすると、別の新しいテキストノードが継続的に追加されます。しかし、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

答えて

3

「私はオートにCSSスタイルを追加するのに問題を抱えているが、textnodeを生成し、」しかし、あなたはを提供したコードを使用すると、すべてのためにheadstyle要素を追加しようとしていることを示しています新しいテキストノード。私はあなたが望むものは、1)あなたのスタイルシートにすでに定義されているスタイルをtextnodeに適用するか、または2)textnodeを直接スタイルすることです。したがって、私はあなたのコードのいずれかされるべきだと思う:

1)span経由textnodeにあなたのCSSスタイルシートにスタイルを適用します。

//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を置きますあなたのコードで行う)、testclassを与えるスパンでtextnodeをラップします。

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

すべてが機能しています。どうもありがとう。どちらの方法も有効です。 –

関連する問題