2012-06-11 65 views
0

我需要更改字体颜色。Javascript更改字体颜色

我有以下几点:

var clr="green"; 

    <font color=clr>' + onlineff + ' </font> 

字体颜色不会更改为绿色。只是想知道如何解决这个问题。

+5

表现标签像

...应该不惜一切避免(标记应当用于语义目的只) 。使用'style'属性代替 – fcalderan

+1

我们需要更多的代码上下文 –

回答

4

不要使用字体颜色是...这真的是老派,一些浏览器甚至不喜欢它了。 使用跨度和CSS:

function givemecolor(thecolor,thetext) 
    { 
    return '<span style="color:'+thecolor+'>'+thetext+'</span>'; 
    } 
document.write(givemecolor('green','I\'m an apple')); 
document.write(givemecolor('yellow','and I\'m a banana')); 
+0

您需要在香蕉行中间跳过引号。 –

+0

谢谢,纠正。 – Tschallacka

1

尝试这样的:

var clr = 'green'; 
var html = '<font color="' + clr + '">' + onlineff + ' </font>'; 

这是说,你应该避免使用<font>标签。现在已被弃用。使用CSS来更改标记中给定元素的样式(颜色)。

+0

它不被弃用*它被删除*(并且没有'color'属性)。 –

+0

'font' is [deprecated](https://developer.mozilla.org/en/HTML/Element/font),因为html 4.01 – MilkyWayJoe

6

考虑更改您的标记是:

<span id="someId">onlineff</span> 

然后你可以使用这个脚本:

var x = document.getElementById('someId'); 
x.style.color = '#00FF00'; 

看到它在这里:http://jsfiddle.net/2ANmM/

4

HTML代码

<div id="coloredBy"> 
    Colored By Santa 
</div> 

JavaScript代码

document.getElementById("coloredBy").style.color = colorCode; // red or #ffffff 

我觉得这是非常容易使用