【问题标题】:Add css style into textnode dynamically动态添加css样式到textnode
【发布时间】:2012-02-03 11:42:04
【问题描述】:

我在将 CSS 样式添加到自动生成的文本节点时遇到问题。我知道 textnode 没有任何父节点。所以我不能只在其中附加 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);
}

有人可以帮我解决这个问题吗?非常感谢。

【问题讨论】:

标签: css textnode


【解决方案1】:

您说:“我在将 css 样式添加到自动生成的文本节点时遇到问题”,但您提供的代码表明您正在尝试为每个新的文本节点添加一个style 元素到head。我认为您想要的是 1) 将样式表中已经定义的样式应用于 textnode,或者 2) 直接设置 textnode 内联样式。因此,我认为您的代码应该是:

1) 通过 span 将 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 放入单元格(您不会在代码中这样做),然后它将用跨度包装文本节点,使其成为classtest

2) 通过span 将样式直接(内联)应用于文本节点:

//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 函数都可以被删除。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-08
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多