Как изменить цвет шрифта определенного значения в объекте? - PullRequest
0 голосов
/ 27 января 2019

Я хочу изменить цвет шрифта значения в объекте, используя JavaScript. Например, я хочу изменить цвет «Ciao»:

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

Я попытался сделать то же, что и другие мои одноклассники, а именно добавить цветовой ключ в объект:

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

Вот мой код:

<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>

Ответы [ 3 ]

0 голосов
/ 27 января 2019

Вам необходимо установить свойство style при отображении котировки.пример:

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;

     }

Это установит цвет, если Quotes[QuoteIndex] имеет свойство color.В противном случае цвет текста будет установлен на black.

Теперь последняя цитата из этого объекта:

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

будет иметь цвет red

0 голосов
/ 27 января 2019

Один из подходов состоит в том, чтобы настроить классы CSS для каждого автора, а затем просто применить класс, соответствующий имени автора (за исключением пробелов, поскольку имена классов не могут содержать пробелы).

Кроме того, выиспользование Pascal Case (т.е. PascalCase) для имен переменных, что противоречит соглашению в JavaScript.Единственный случай, когда следует использовать Pascal Case, с именами функций-конструкторов как способ сообщить другим, что эти функции должны вызываться с ключевым словом new.Все заглавные буквы часто (но не обязательно) используются с именами констант, но кроме этого, для идентификаторов следует использовать регистр верблюдов (camelCase).

Кроме того, не используйте встроенные атрибуты событий HTML.Есть куча причин не использовать эту технику 20+ лет, которая просто не умрет.Вместо этого делайте всю работу JavaScript отдельно от 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 голосов
/ 27 января 2019

Вы можете установить такой цвет, например, 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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...