将单词更改为不同的颜色

时间:2015-03-15 21:39:56

标签: javascript text colors

所以我有这段代码:

<script type="text/javascript">
    document.getElementById("randoBtn").addEventListener("click", clickHandler);

function clickHandler(event) {
    event.preventDefault();
    document.getElementById("message1").innerHTML = "Try writing a " + selectedWord() + " and";
    var selectWord  
    document.getElementById("message2").innerHTML = selectedWord() + " story";
}

function selectedWord(){
    var myarray = new Array("Action", "Adventure", "Apocalyptic", "Comedy", "Detective", "Disaster", "Drama", "Epic", "Erotica", "Fable", "Fairy Tale", "Fantasy", "Fiction", "Folk Tale", "Ghost", "Historical", "Horror", "Humor", "Military", "Mystery", "Mythology", "Narrative", "Parallel Universe", "Paranormal", "Parody", "Poetry", "Post-Apocalyptic", "Pulp Fiction", "Quest", "Realistic Fiction", "Revenge", "Romantic", "Science Fiction", "Short Story", "Spy", "Supernatural", "Tall Tale", "Thriller", "Time Travel", "Undersea", "Western");

    return myarray[Math.round(Math.random() * (myarray.length - 1))];
}   
</script>

无论如何只将selectWord()变量更改为其他颜色?我只是想让它与其他文本脱颖而出。提前谢谢!

1 个答案:

答案 0 :(得分:0)

这里我用<span>标签包装了selectedWord返回,只要它跨越一个类名并设置了类名。

function clickHandler(event) {
    event.preventDefault();
    document.getElementById("message1").innerHTML = "Try writing a <span class=\"Words\">" + selectedWord() + "</span> and";
    var selectWord  
    document.getElementById("message2").innerHTML = "<span class=\"Words\">"+selectedWord() + "</span> story";
}
function selectedWord(){
    var myarray = new Array("Action", "Adventure", "Apocalyptic", "Comedy", "Detective", "Disaster", "Drama", "Epic", "Erotica", "Fable", "Fairy Tale", "Fantasy", "Fiction", "Folk Tale", "Ghost", "Historical", "Horror", "Humor", "Military", "Mystery", "Mythology", "Narrative", "Parallel Universe", "Paranormal", "Parody", "Poetry", "Post-Apocalyptic", "Pulp Fiction", "Quest", "Realistic Fiction", "Revenge", "Romantic", "Science Fiction", "Short Story", "Spy", "Supernatural", "Tall Tale", "Thriller", "Time Travel", "Undersea", "Western");

    return myarray[Math.round(Math.random() * (myarray.length - 1))];
}  
window.onload=function(){document.getElementById("randoBtn").addEventListener("click", clickHandler);}
.Words{color:red;font-weight:bold;}
    <button id="randoBtn">Go!</button>
<div id="message1"></div>
<div id="message2"></div>

我希望这会有所帮助。快乐的编码!