gpt4 book ai didi

javascript - 如何更改对象中特定值的字体颜色?

转载 作者:行者123 更新时间:2023-11-28 00:31:35 24 4
gpt4 key购买 nike

我想使用 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>

最佳答案

渲染报价时需要设置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"}]

将有颜色红色

关于javascript - 如何更改对象中特定值的字体颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54383278/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com