簡體   English   中英

如何使用JavaScript更改文本顏色

[英]How to change text color using 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>

據我了解,您已經創建了Quoted和Author變量,這些變量選擇了這些ID,但是在if語句中,您已將Quotes變量分配為數組,並且與DOM沒有任何關系

但是,要解決該問題,必須在if語句中使用Quote ,如下所示:

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

我希望這個答案會有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM