如何使用javascript更改元素的颜色

时间:2015-05-06 16:03:45

标签: javascript colors

我正在参加初学者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 = "";
    }

}

1 个答案:

答案 0 :(得分: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您的变量。