2016-11-01 90 views
1

這聽起來像是一個很容易解決的問題。誠然,我曾希望能夠做到這一點。我想要一個字符串,有兩種顏色。在JS:一種功能中的兩種顏色的字符串?

function twoColors(s1,s2) { 
    s1.color = "#hexColor1"; 
    s2.color = "#hexColor2"; 
    return(s1+s2) 
} 
在HTML

(在JS採購後)

<script> 
    document.getElementById("theElementsID").innerHTML = twoColors("one","two"); 
</script> 

然而,這不工作... 想法?

+4

字符串沒有顏色。你需要用CSS編寫HTML標籤。 – SLaks

+0

它可能正常工作,但's1'和's2'是字符串,並且由於某種原因,您爲字符串添加了'color'屬性 – adeneo

+0

@ j08691對不起,我沒有複製粘貼功能,但它在我的代碼中。 – SumNeuron

回答

2

您需要使用樣式將文本包裝在HTML中。

function twoColors(s1, s2) { 
 
    s1 = "<span style=\"color:#eeff00\">" + s1 + "</span>"; 
 
    s2 = "<span style=\"color:#00eeff\">" + s2 + "</span>"; 
 
    return (s1 + s2) 
 
} 
 
document.getElementById("output").innerHTML = twoColors("one", "two");
<div id="output" style="background-color:black;">123</div>

+0

什麼是+ s1 +? – SumNeuron

+0

你需要像這樣看到它:'s1 = string + variable + string' –

1

如果有一個很好的理由不使用CSS,那麼你可以做:

function twoColors(s1,s2) { 
 
    var container = document.createElement('div'); 
 
    var el1 = document.createElement('span'); 
 
     el1.style.color = "#33aa33"; 
 
     el1.textContent = s1; 
 
    container.appendChild(el1); 
 
    var el2 = document.createElement('span'); 
 
     el2.style.color = "#aa3333"; 
 
     el2.textContent = s2; 
 
    container.appendChild(el2) 
 
    return(container) 
 
} 
 
document.getElementById("theElementID").appendChild(twoColors("one","two"));
<div id="theElementID"></div>