根据数字使用Javascript更改文本颜色

时间:2018-02-09 15:26:53

标签: javascript

如果答案为“7”,我需要将文本颜色更改为红色,如果是“13”或“24”,则需要将文本颜色更改为绿色。我尝试过几种不同的东西,但似乎无法让它发挥作用。我不知道是否有人知道我做错了什么,但任何帮助都会受到赞赏。

do {
  var luckyNumber = prompt('What is your lucky number?', "");
  luckyNumber = parseInt(luckyNumber, 10);
} while (isNaN(luckyNumber));


if (luckyNumber == 7) {
  document.write("<p>Hey, 7 is my lucky number too!</p>").style.color = "red";
} else
if (luckyNumber == 13 || luckyNumber == 24) {
  document.write("<p>Wooh. " + luckyNumber + "? That's an unlucky number!</p>").style.color = "green";
} else {
  document.write("<p>The number " + luckyNumber + " is lucky for you!</p>");
}

3 个答案:

答案 0 :(得分:4)

问题是因为document.write()没有返回您可以调用style.color的元素。这就是您在控制台中看到错误的原因。你也应该避免使用document.write,因为这是非常糟糕的做法。

相反,使用document.createElement()将新元素添加到DOM。从那里你可以简单地添加类,通过CSS规则应用所需的颜色。像这样:

do {
  var luckyNumber = parseInt(prompt('What is your lucky number?', ""), 10);
} while (isNaN(luckyNumber));

var p = document.createElement('p');
document.body.appendChild(p);

if (luckyNumber == 7) {
  p.textContent = 'Hey, 7 is my lucky number too!';
  p.classList.add('red');
} else
if (luckyNumber == 13 || luckyNumber == 24) {
  p.textContent = `Wooh. ${luckyNumber}? That's an unlucky number!`;
  p.classList.add('green');
} else {
  p.textContent = `The number ${luckyNumber} is lucky for you!`;
}
.red { color: #C00; }
.green { color: #0C0; }

答案 1 :(得分:1)

如何使用内联样式属性呢?

do {
  var luckyNumber = prompt('What is your lucky number?',"");
  luckyNumber = parseInt(luckyNumber, 10);
} while (isNaN(luckyNumber));

if (luckyNumber == 7) {
  document.write("<p style='color:red;'>Hey, 7 is my lucky number too!</p>");
} else if (luckyNumber == 13 || luckyNumber == 24) {
  document.write("<p style='color:green;'>Wooh. " + luckyNumber + "? That's an unlucky number!</p>");
} else {
  document.write("<p>The number " + luckyNumber + " is lucky for you!</p>");
}

答案 2 :(得分:0)

您可以通过添加&#34; style =&#39; color:(color)&#39;&#34;来更改html标记中的颜色。 你可以使用这样的东西

&#13;
&#13;
<script>
var luckyNumber = 7;
if (luckyNumber == 7) {
        document.write("<p style='color:red'>Hey, 7 is my lucky number too!</p>");
    } else if (luckyNumber == 13 || luckyNumber == 24) {
        document.write("<p style='color:green'>Wooh. " + luckyNumber + "? That's an unlucky number!</p>");
    } else {
        document.write("<p>The number " + luckyNumber + " is lucky for you!</p>");
    }
</script>
&#13;
&#13;
&#13;