使用javascript设置html文本颜色和大小

Geo*_*ge2 20 html javascript

假设我在html中有以下代码行,如何使用Javascript以简单的方式在编程方式中设置"MonitorInformation"DIV元素中的文本颜色和大小?对不起我的愚蠢,我想了很长时间,但想不通.:-(

<div id="MonitorInformation">Connecting...wait</div>
Run Code Online (Sandbox Code Playgroud)

乔治,提前谢谢

Ant*_*nes 35

var elem = document.getElementById("MonitorInformation");
elem.innerHTML = "Setting different HTML content";
elem.style.color = "Red";
elem.style.fontSize = "large";
Run Code Online (Sandbox Code Playgroud)

  • 建议使用实际值(例如`#FFF`,`0.7em`)而不是`Red`,`large`来坚持标准. (3认同)

Rus*_*Cam 5

var myDiv = document.getElementById("MonitorInformation");
myDiv.style.fontSize = "11px";
myDiv.style.color = "blue";
Run Code Online (Sandbox Code Playgroud)

看看JavaScript样式属性


med*_*iev 5

我已经抽象了一些方法,这可以使它们对多个调用更有用:

var el = document.getElementById("MonitorInformation");

function text( el, str ) {
    if ( el.textContent ) {
         el.textContent = str;
    } else {
         el.innerText = str;
    }
}

function size ( el, str ) {
     el.style.fontSize = str;
}

function color ( el, str ) {
     el.style.color = str;
}

size( el, '11px') 
color( el, 'red' )
text(el, 'Hello World')
Run Code Online (Sandbox Code Playgroud)

注意:动态更改此类内容的最佳做法是在单独的外部选择器中设置样式:

.message {color:red; 字体大小:1.1em; }

并切换类名,.className + ='message'(或添加/删除类的抽象函数).