繁体   English   中英

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

[英]how to change color of an element with 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 = "";
    }

}

在循环中,检查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 (对于现代浏览器)。 在较老的浏览器中,您必须手动将className作为字符串操作。

另外,您应该始终对变量进行var更改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM