2013-07-07 94 views
2
chatTextBox.innerHTML = '<span style="color:#FF0000"> hi </span>'; 

這就是我想做的事,但剛剛的innerHTML成爲的innerHTML並改變顏色

<span style="color:#FF0000"> hi </span> 

,並以紅色不hi

注:我正在使用TextArea,我希望能夠以多種文字顏色書寫。

回答

1
chatTextBox.value = 'hi'; 
chatTextBox.style.color = 'red'; 

現在,如果你想擁有你不能用一個textarea你將不得不使用某種CONTENTEDITABLE元素的許多不同顏色的文字。

+0

我的目標是在同一個TextArea上有不同的顏色文本......那麼我現在該做什麼?可滿足的元素? – PerfectAffix

+0

@PerfectAffix這就是我所說的。 – Musa

+0

是的,什麼是可以理解的元素?我是否需要設置contenteditable ='true',並且我正在嘗試使用TextArea會起什麼作用? – PerfectAffix

1

風格訪問是這樣的:

document.getElementById("chatTextBox").style.visibility = 'hidden'; 
document.getElementById('chatTextBox').innerHTML = "Hello"; 
2

chatTextBox.innerHTML = 「<span style='color:#FF0000'> hi </span>」;

嘗試這種方式,它應該理想地工作。

+0

這實際上工作,它幫助了我。 – Winona

1

我不知道這是你想要的,但看看這Codepen!它隨機更改輸入框的顏色。這裏的HTML以下:

<div style="height:150px"> 
    <h1>Type in the Input BOX below and see changing colors as you type!!</h1> 
    <br><br> 
    <input type="text" id="multi" style="width:100%; height:100px; font-size:26px;" onkeydown="myFunction()"> 
</div> 


這裏是JS:

var myArray = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']; 
function myFunction(){ 
var rand = myArray[Math.round(Math.random() * (myArray.length - 1))]; 
var rand1 = myArray[Math.round(Math.random() * (myArray.length - 1))]; 
var rand2 = myArray[Math.round(Math.random() * (myArray.length - 1))]; 
var rand3 = myArray[Math.round(Math.random() * (myArray.length - 1))]; 
var rand4 = myArray[Math.round(Math.random() * (myArray.length - 1))]; 
var rand5 = myArray[Math.round(Math.random() * (myArray.length - 1))]; 

document.getElementById("multi").style.color = '#'+rand+rand1+rand2+rand3+rand4+rand5; 
} 

P.S。我是新來的Java腳本,但我試圖幫助!

0

這可能與contenteditable元素。綜上所述,您可以使用contenteditable屬性將任何元素轉換爲類似textarea的元素。該contenteditable屬性可以讓你在<p>標籤類型,像這樣:

<p contenteditable="true" id="changeColor">Click to type</p> 

因爲contenteditable元素不是textarea,您可以添加在它裏面實際的代碼。使用contenteditable<p>標記,您可以插入您在問題中向我們顯示的<span>標記。爲了更改contenteditable元素的顏色,您必須使用javascript命令:document.execCommand()。如果您需要使用execCommand()的幫助,我發現很好的link這樣做。如果您需要示例,則document.execCommand('bold')會將任何選定的文本轉換爲粗體文本。這聽起來很簡單,但相對困難。祝你的項目好運!