如何使用JavaScript更改文本颜色

时间:2019-01-24 23:23:05

标签: javascript

我希望我的引号的颜色与非我的引号不同。不属于我的语录我想成为黑色。

您好,对于一项作业,我必须更改文档以随机显示在文档上的引号,添加自己的引号并更改其文本颜色。我曾尝试这样做,但我的引号不会改变颜色。请帮忙。

<html>

   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      <title>My Web Page Of Wisdom</title> 
      <style type="text/css">
         .full-page { position:absolute; top:0; right:0; bottom:0; left:0; }
         .x-center-y-center-column { display:flex; flex-direction:column; justify-content:center; align-items:center; }
         .quote { padding:0.5em; text-align:center; font-size:1.5rem; color:#336699; }
         .author { text-align:center; font-size:1rem; color:#a0a0a0; opacity:1.0; transition:all 1.0s; }
         .navigation-buttons { position:absolute; bottom:1.0em; }
      </style> 
   </head>
  <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="OnNext()">></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:"This is a quote.", Author: "Danny", color: "#ff0000" },
            { Text:"This is quote 2.", Author: "Danny", color: "#0000FF" },
            { Text:"This is quote 3.", Author: "Danny", color: "#FF7F50" }
         ]

         OnNext = () => {
            CurrentQuoteIndex = Math.floor( Math.random() * Quotes.length ) + 1;
            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;

             if( Quotes[QuoteIndex].color )
                 {
                     Quotes.style.color = Quotes[QuoteIndex].color;
                 }
             else 
             {
                 Quotes.style.color = "#000000";
             }
         }
      </script>
 </body>

</html>

1 个答案:

答案 0 :(得分:1)

据我了解,您已经创建了 Quote和Author 变量,这些变量选择了这些ID,但是在 if 语句中,您分配了 Quotes 变量,它是一个数组,并且与 DOM

没有任何关系

但是,要解决该问题,您必须在 if 语句中使用 Quote (报价),如下所示:

if (Quotes[QuoteIndex].color) {
    Quote.style.color = Quotes[QuoteIndex].color;
} else {
    Quote.style.color = "#000000";
}

我希望这个答案会有用。