如何在JavaScript中为内容添加样式?

Ash*_*ley 5 javascript fonts coding-style colors

我一直在使用JavaScript文件,我的内容一直在使用短语.现在我想改变那些短语的风格.第一个函数(请参阅函数swapFE)我想将短语节点的字体样式更改为正常.并将短语节点的颜色更改为颜色值(155,102,102).第二个函数(参见swapEF)我想将字体样式更改为斜体,将字体颜色更改为黑色.我怎么写这些?我是在JavaScript中使用这些函数编写的,还是直接在CSS或HTML中应用样式更改?

这些是我想要将样式更改应用到的两个函数:

    //this function changes the French phrase to an English phrase.
function swapFE(e) {
       var phrase = e.srcElement; 
       //phrase.innerText = english[phrase.id];
    var parent = phrase.parentNode;
    //childNodes[0] is the number of the phrase +1 
    var idnum = parent.childNodes[0];
    //parseInt takes a textstring and extracts it to make a number. Then you will subtract 1 from the number.
    var phrasenum = parseInt(idnum.innerHTML)-1;
    phrase.innerText = english[phrasenum];

  }


function swapEF(e) {
       var phrase = e.srcElement; 
       //phrase.innerText = english[phrase.id];
    var parent = phrase.parentNode;
    var idnum = parent.childNodes[0];
    var phrasenum = parseInt(idnum.innerHTML)-1;
    phrase.innerText = french[phrasenum];
Run Code Online (Sandbox Code Playgroud)

如果你甚至可以给我一个参考,我可以找到这些属性很棒.

Tor*_*amo 10

obj.style.whicheverProperty = "value"
Run Code Online (Sandbox Code Playgroud)

例如:

document.getElementById('mydiv').style.fontVariant = "italic";
Run Code Online (Sandbox Code Playgroud)

您正在寻找的Google关键字是HTML DOM(文档对象模型),它将各种样式定义为对象样式成员的属性.


Ash*_*ley 0

我想出了如何添加样式更改。通过编写parent.childNodes[1].style.fontStyle=“正常”或“斜体”(取决于功能);并且parent.childNodes[1].style.color =“黑色”。

//this function changes the French phrase to an English phrase.
    function swapFE(e) {
           var phrase = e.srcElement; 
           //phrase.innerText = english[phrase.id];
           var parent = phrase.parentNode;
           //childNodes[0] is the number of the phrase +1 
           var idnum = parent.childNodes[0];
           //parseInt takes a textstring and extracts it to make a number. Then you will subtract 1 from the number.

       var phrasenum = parseInt(idnum.innerHTML)-1;
       phrase.innerText = english[phrasenum];
       parent.childNodes[1].style.fontStyle= "normal";
         //Below is the correct way to write an RGB style.
         parent.childNodes[1].style.color = "rgb(155, 102, 102)";
}


function swapEF(e) {
       var phrase = e.srcElement; 
       //phrase.innerText = english[phrase.id];
       var parent = phrase.parentNode;
       var idnum = parent.childNodes[0];
       var phrasenum = parseInt(idnum.innerHTML)-1;
       phrase.innerText = french[phrasenum];
       parent.childNodes[1].style.fontStyle= "italic";
       parent.childNodes[1].style.color= "black";
Run Code Online (Sandbox Code Playgroud)