通过javascript代码更改html中的文本颜色

时间:2014-12-29 12:02:10

标签: javascript html colors

我正在尝试更改标题颜色,因为我在下面的html代码和颜色的颜色 文本没有改变。 我怎么能改变它?

 /**
     * Build a HTML table with the data
     */
    Highcharts.Chart.prototype.getTable = function () {
        var title =this.title.text; 
        var device = this.series[0].name;
        var unit = this.series[0].yAxis.axisTitle.text;

       // var html = '<table>',
        var html = '<h1 style="color:red">'+title+'</h1> <h2 style="color:red" >Device: '+device+'</h2><h2 style="color:red" >Unit: '+unit+'</h2>'+
        '<table>',
            rows = this.getDataRows();
        html += '</table>';
        return html;
    };

谢谢,Michal

3 个答案:

答案 0 :(得分:1)

使用以下内容代替在javascript中编写HTML代码:

document.getElementById("Your_element_Id").style.color="Any_color";

答案 1 :(得分:0)

您可以使用此

document.getElementById("h1").style.color = "red";

通过。 http://www.w3schools.com/js/js_htmldom_css.asp

答案 2 :(得分:0)

如果你想对多个元素运行相同的功能,由它们的tagName(h1h2等)标识,我建议:

function colorise() {
  // using the forEach method of the Array.prototype,
  // iterating over the array-like result of calling querySelectorAll():
  Array.prototype.forEach.call(document.querySelectorAll('h1, h2'), function(h) {
    // h: the current array-element (in this case a node) of the array over 
    // which we're iterating.
    h.style.color = 'red';
  });

  // irrelevant, just to prevent subsequent (non-functional) clicks on the button:
  this.disabled = true;
  // further emphasising the disabled nature of the button:
  this.style.opacity = 0.5;
}

// finding the first <button> element, and adding an event-listener,
// listening for the 'click' event, and running a function in response:
document.querySelector('button').addEventListener('click', colorise);

&#13;
&#13;
function colorise() {
  Array.prototype.forEach.call(document.querySelectorAll('h1, h2'), function(h) {
    h.style.color = 'red';
  });
  this.disabled = true;
  this.style.opacity = 0.5;
}
document.querySelector('button').addEventListener('click', colorise);
&#13;
<h1>H1 text</h1>
<h2>H2 text</h2>
<h1>More H1 text</h1>
<h2>And another h2</h2>

<button>Change the heading elements' text to red</button>
&#13;
&#13;
&#13;

参考文献: