通过JavaScript代码更改HTML中的文本颜色

change text color in html via javascript code

本文关键字:文本 颜色 HTML JavaScript 代码 通过      更新时间:2023-09-26

我正在尝试更改标题颜色,因为我在下面的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;
    };

谢谢,米哈尔

使用以下内容而不是用javascript编写HTML代码:

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

你可以使用这个

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

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

如果你想在多个元素上运行相同的函数,由它们的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);

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);
<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>

引用:

  • Array.prototype.forEach() .
  • document.querySelector() .
  • document.querySelectorAll() .
  • Function.prototype.call() .