2012-06-11 64 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 

我覺得這是非常容易使用