How do I add style to content in JavaScript?

后端 未结 4 1779
独厮守ぢ
独厮守ぢ 2021-01-13 08:02

I have been working in a JavaScript file and my content has been working with phrases. Now I want to change the style of those phrases. The first function (see function swap

相关标签:
4条回答
  • 2021-01-13 08:16

    You could also just change a class to the element ..

    in the swapFE function

    phrase.className = 'english';
    

    and in the swapEF function

    phrase.className = 'french';
    

    and in your css file

    .english{ color:#9b6666; }
    .french{ font-style:italic; color:#000; }
    
    0 讨论(0)
  • 2021-01-13 08:23

    Using element.style you can change css from Javascript.

    For example:

    document.getElementById('mydiv').style.backgroundColor = 'red';
    

    And to help you find the exact syntax for the attribute, here's CSS Properties To JavaScript Reference Conversion.

    0 讨论(0)
  • 2021-01-13 08:38
    obj.style.whicheverProperty = "value"
    

    for instance:

    document.getElementById('mydiv').style.fontVariant = "italic";
    

    The google keyword you're looking for is HTML DOM (document object model), which defines the various styles as properties of an object's style member.

    0 讨论(0)
  • I figured out how to add the style changes. By writing parent.childNodes[1].style.fontStyle= "normal" or "italic" (depending on the function); and parent.childNodes[1].style.color = "black".

    //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";
    
    0 讨论(0)
提交回复
热议问题