2015-05-06 59 views
0

我正在學習一個初學者的javascript類。我的老師希望我改變頁面中元素的顏色,但我無法弄清楚如何去做。這裏是頁面:如何用javascript更改元素的顏色

// JavaScript Document 

function myPar() { 

    pge = new Array() 

    //I would need to change the color of JUST pge[4] 

    pge[4] = "So have you reverse engineered this document?" 

    pge[3] = "This first instance a button creation will create multiple buttons with no purpose. They will not be linked to any site in this lecture video. The first need to become familiar with the process and with the required syntax for setting a series of attributes. When the button construction sequence is completed the process will then append the button to the body tag as it did for the paragraph tag." 

    pge[2] = "The same process that was used to create paragraphs dynamically will be used to create buttons dynamically. This first instance of button creation will be design to create a button each time the function trigger is pressed." 

    pge[5] = "So this build of page content can happen in any sequence that is seen fit and then modified by changing index vaues." 

    pge[0] = "It was the best of times, it was the worst of times" 

    pge[1]= "There's no way that we can work out a way to colonize Mars in the next 50 years. Think of the logistical obstacles to such a plan. You'd need food, water, medicine. You'd need engineers, doctors, nurses, endless oxygen, of which mars has none." 

    pge[6] = "So what is such a big deal here?" 


    for (i=0;i<=pge.length-1;i++) { 
     var pgp = document.createElement("p"); 
     var txt = document.createTextNode(pge[i]); 

     pgp.appendChild(txt); 
     pgp.setAttribute("class","mine"); 

     pgp.appendChild(document.createElement("br")); 

     pgp.setAttribute("style","color:#605;font-size:1.5em;"); 

     document.body.appendChild(pgp); 
     txt = ""; 
    } 

} 

回答

0

在你的循環中,檢查i的值。如果它是4,那麼它就是你想改變的那個。所以,你可以做這樣的事情:

var len = pge.length; 
for (var i=0; i< len;i++) { 
if (i==4) { pgp.classList.add('redBG'); } 
} 

而且有一個CSS類:

.redBG {background-color:red; } 

更新class,最好的辦法是不使用setAttribute。它通過修改classList(適用於現代瀏覽器)。在較舊的broswers中,您必須手動操作className作爲字符串。

此外,你應該總是var你的變量。