Je souhaite modifier la couleur de police d'une valeur dans un objet à l'aide de JavaScript. Par exemple, je veux changer la couleur de "Ciao":

     const Quotes = [{Text: "Hello", Author: "Him"},
     {Text: "Goodbye", Author: "Her"},
     {Text: "Ciao", Author: "Me"}]

J'ai essayé de faire ce que mes autres camarades de classe ont fait qui est d'ajouter la clé de couleur dans l'objet:

     const Quotes = [{Text: "Hello", Author: "Him"},
     {Text: "Goodbye", Author: "Her"},
     {Text: "Ciao", Author: "Me", "color":"red"}]

Voici mon code:

<body onload="RenderQuote(0)">
  <section class="full-page x-center-y-center-column">
     <div id="quote-block" class="quote"></div>
     <div id="author-block" class="author"></div>
     <div class="navigation-buttons">
        <button onclick="RandomQuote()">Random</button>
     </div>            
  </section>
  <script>
     let CurrentQuoteIndex = 0;
     const Quotes = [
        { Text:"Apparently there is nothing that cannot happen today.", Author:"Mark Twain" },
        { Text:"The world's most famous and popular language is music.", Author:"Henri de Toulouse-Lautrec" },
        { Text:"Life is like riding a bicycle.<br>To keep your balance you must <b>keep moving</b>.", Author:"Albert Einstein" },
        { Text:"Life is a marathon, know when to take a break.", Author:"My Name" },
        { Text:"Take care of yourself as if you're taking care of someone else.", Author:"My Name" },
        { Text:"Remember to take your pills.", Author:"My Name" }
     ]
     RandomQuote = () => {
        CurrentQuoteIndex = Math.floor(Math.random() * (Quotes.length));
        RenderQuote(CurrentQuoteIndex);
     }
     RenderQuote = (QuoteIndex) => {
        let Quote = document.getElementById("quote-block");
        let Author = document.getElementById("author-block");

        Quote.innerHTML = Quotes[QuoteIndex].Text;

        Author.innerHTML = Quotes[QuoteIndex].Author;

     }
  </script>
0
vin_tay 27 janv. 2019 à 01:11

3 réponses

Meilleure réponse

Vous devez définir la propriété style lors du rendu du devis. exemple:

RenderQuote = (QuoteIndex) => {
        let Quote = document.getElementById("quote-block");
        let Author = document.getElementById("author-block");
        let authorName = Quotes[QuoteIndex].Author;


        Quote.innerHTML = Quotes[QuoteIndex].Text;
        // set quote texts color
        Quote.style.color = Quotes[QuoteIndex].color || 'black';

        Author.innerHTML = authorName;

     }

Cela définira la couleur si Quotes[QuoteIndex] a la propriété color. Sinon, la couleur du texte sera définie sur black.

Maintenant dernière citation de cet objet:

 const Quotes = [{Text: "Hello", Author: "Him"},
 {Text: "Goodbye", Author: "Her"},
 {Text: "Ciao", Author: "Me", color:"red"}]

Aura la couleur red

0
mjanisz1 26 janv. 2019 à 22:52

Vous pouvez définir une couleur comme celle-ci, par exemple Quote.style.color = 'rgb(244,123,234)'

<body onload="RenderQuote(0)">
  <section class="full-page x-center-y-center-column">
     <div id="quote-block" class="quote"></div>
     <div id="author-block" class="author"></div>
     <div class="navigation-buttons">
        <button onclick="RandomQuote()">Random</button>
     </div>            
  </section>
  <script>
     let CurrentQuoteIndex = 0;
     const Quotes = [
        { Text:"Apparently there is nothing that cannot happen today.", Author:"Mark Twain" },
        { Text:"The world's most famous and popular language is music.", Author:"Henri de Toulouse-Lautrec" },
        { Text:"Life is like riding a bicycle.<br>To keep your balance you must <b>keep moving</b>.", Author:"Albert Einstein" },
        { Text:"Life is a marathon, know when to take a break.", Author:"My Name" },
        { Text:"Take care of yourself as if you're taking care of someone else.", Author:"My Name" },
        { Text:"Remember to take your pills.", Author:"My Name" }
     ]
     RandomQuote = () => {
        CurrentQuoteIndex = Math.floor(Math.random() * (Quotes.length));
        RenderQuote(CurrentQuoteIndex);
     }
     RenderQuote = (QuoteIndex) => {
        let Quote = document.getElementById("quote-block");
        let Author = document.getElementById("author-block");
        let authorName = Quotes[QuoteIndex].Author;
        
        
        Quote.innerHTML = Quotes[QuoteIndex].Text;
        if(authorName=='My Name') {
            Quote.style.color = `red`;
        } else {
            Quote.style.color = `black`;
        }

        Author.innerHTML = authorName;

     }
  </script>
0
Kamil Kiełczewski 26 janv. 2019 à 22:31

Une approche consisterait à configurer des classes CSS pour chaque auteur, puis à appliquer simplement la classe qui correspond au nom de l'auteur (moins les espaces car les noms de classe ne peuvent pas contenir d'espaces).

De plus, vous utilisez Pascal Case (c'est-à-dire PascalCase) pour vos noms de variables, ce qui va à l'encontre des conventions en JavaScript. Le seul cas où Pascal Case doit être utilisé est avec les noms de fonctions constructeur pour faire savoir aux autres que ces fonctions doivent être appelées avec le mot clé new. Toutes les majuscules sont souvent utilisées (mais pas obligatoires) avec des noms constants, mais à part cela, la camel case (camelCase) doit être utilisée pour les identifiants.

N'utilisez pas non plus d'attributs d'événements HTML en ligne. Il existe un tas de raisons de ne pas utilisez cette technique vieille de plus de 20 ans qui ne mourra pas. Au lieu de cela, faites tout votre travail JavaScript séparément du HTML.

document.querySelector("button").addEventListener("click", randomQuote);

let currentQuoteIndex = 0;
const quotes = [
  { text:"Apparently there is nothing that cannot happen today.", author:"Mark Twain" },
  { text:"The world's most famous and popular language is music.", author:"Henri de Toulouse-Lautrec" },
  { text:"Life is like riding a bicycle.<br>To keep your balance you must <b>keep moving</b>.", author:"Albert Einstein" },
  { text:"Life is a marathon, know when to take a break.", author:"My Name" },
  { text:"Take care of yourself as if you're taking care of someone else.", author:"My Name" },
  { text:"Remember to take your pills.", author:"My Name" }
];
 
function randomQuote(){
  currentQuoteIndex = Math.floor(Math.random() * (quotes.length));
  renderQuote(currentQuoteIndex);
}

function renderQuote(quoteIndex){
  let quote = document.getElementById("quote-block");
  let author = document.getElementById("author-block");
  
  quote.classList = "quote";    // Reset the class list
  
  // Replace spaces in the author name with nothing and use that resulting
  // string as the class name to apply to the <div> that is the quote
  quote.classList.add(quotes[quoteIndex].author.replace(/\s+/g, ""));
  
  quote.innerHTML = quotes[quoteIndex].text;
  author.innerHTML = quotes[quoteIndex].author;
}
button { margin:10px 0; }
.quote { font-size:1.5em; font-weight:bold; }
.author { font-style:italic; margin-left:15px; }

/* Each author's name becomes a CSS class and each gets a color. */  
.AlbertEinstein { color: green; }
.HenrideToulouse-Lautrec { color: blue; }
.MarkTwain { color: orange; }
.MyName { color: purple; }
<section class="full-page x-center-y-center-column">
  <div class="navigation-buttons">
    <button>Random</button>
  </div>   
  <div id="quote-block" class="quote"></div>
  <div id="author-block" class="author"></div>
</section>
0
Scott Marcus 26 janv. 2019 à 23:37