我创建了一个简单的计算器,可以根据您在课堂上获得的分数告诉您所获得的字母等级。但是,我正在尝试格式化document.write()的文本。我不仅希望简单地打印文本,还希望它打印出具有特定大小的字体,网页内特定的背景颜色的文本(仅在document.write()的输出附近),并且还希望在生成的输出下划线。

<html>
 <head><title>Letter-Grade Calculator</title></head>
 <body>
 <h3>Letter-Grade Calculator</h3>
  <script type="text/javascript">

     var score = parseFloat(prompt ("What is your score?"));

     if (score >= 90){
         document.write("The score you entered is: " + score + ". Your letter grade is: A!");
 }
     else if (score >= 80 && score <= 89.9){
         document.write("The score you entered is: " + score + ". Your letter grade is: B!");
 }
     else if (score >= 70 && score <= 79.9){
         document.write("The score you entered is: " + score + ". Your letter grade is: C!");
 }
     else if (score >= 60 && score <= 69.9){
         document.write("The score you entered is: " + score + ". Your letter grade is: D!");
 }
     else {
         document.write("The score you entered is: " + score + ". Your letter grade is: F!");
 }

  </script>
 </body>
</html>


我已经厌倦了将每个document.write()中的文本分配给特定变量,然后在document.write()中调用该变量(例如:说我有一个变量'gradeA',然后将第一个if条件设置为返回' document.write(gradeA);'如果为true),然后使用我在网上找到的某些扩展名尝试修改该变量。但是我无法获得所需的输出。

最佳答案

使用CSS和标签...

<html>
 <head><title>Letter-Grade Calculator</title></head>
 <body>
 <h3>Letter-Grade Calculator</h3>
 <style>
    .red {background: red;};
    .blue {background: blue;};
    .green {background: green;};
    .yellow {background: yellow;};
    .black {background: black;};
 </style>
  <script type="text/javascript">

     var score = parseFloat(prompt ("What is your score?"));

     if (score >= 90){
         document.write("<span class='red'>The score you entered is: " + score + ". Your letter grade is: A!</span>");
 }
     else if (score >= 80 && score <= 89.9){
         document.write("<span class='green'>The score you entered is: " + score + ". Your letter grade is: B!</span>");
 }
     else if (score >= 70 && score <= 79.9){
         document.write("<span class='blue'>The score you entered is: " + score + ". Your letter grade is: C!</span>");
 }
     else if (score >= 60 && score <= 69.9){
         document.write("<span class='yellow'>The score you entered is: " + score + ". Your letter grade is: D!</span>");
 }
     else {
         document.write("<span class='black'>The score you entered is: " + score + ". Your letter grade is: F!</span>");
 }

  </script>
 </body>
</html>

关于javascript - 在JavaScript中格式化document.write()的输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33286610/

10-11 22:22
查看更多