有没有办法将变量作为HTML中的值?

时间:2020-01-09 13:16:16

标签: javascript html variables

我正在做一个简单的副项目,无法弄清楚如何将“ varColor”变量的值作为网页的背景色。 (我省略了代码的lightswitch部分,因为它可以正常工作)

我尝试了多种方法来调用该值,但尚未得到任何结果。

好吧,所以我从答案中尝试了许多方法,但似乎无法根据电灯开关的值做出反应。也有一些帮助吗?

<head>  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <p id="varColor"></p>

  <script>
  window.onload
  var color = "white"
  if(id.lightSwitch == true)
  {
      var color = "white";
  }
  if(id.lightSwitch == false){
      var color = "black";
  }

  document.getElementById("varColor").innerHTML = color;
</script>

    <title>Link catalog</title>
    <style>
    body {
    background-color: color;
}
</style>
  </head>



<font style= "color:#ffffff"><i>lightSwitch</i></font>
        <div class="onoffswitch">
        <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="lightSwitch">
        <label class="onoffswitch-label" for="lightSwitch">
            <span class="onoffswitch-inner"></span>
            <span class="onoffswitch-switch"></span>
        </label>
    </div>

新代码与原始文件位于页面底部的位置相同。

是的,我知道当页面为白色时这些单词是不可见的,我将在启用开关功能后对其进行修复。

4 个答案:

答案 0 :(得分:3)

您可以像这样更新其样式:

document.querySelector('#varColor').style.background = color;

您不需要调用window.location.reload();

答案 1 :(得分:2)

只需在Javascript中定义一个变量,例如:var varColor = gray

,然后分配此变量 varColor 来设置HTML文档的背景颜色,例如document.body.style.background = varColor

下面是一个示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Your body content goes here.</h1>
    <script>
        var varColor = "yellow";
        document.body.style.background = varColor;
    </script>
</body>
</html>

答案 2 :(得分:1)

要设置html正文的背景颜色,您可以使用:

document.body.style.backgroundColor = color;

要设置varColor元素的背景色,您可以使用:

document.getElementById('varColor').style.backgroundColor = '#000';

我认为应该是您的示例,它将颜色设置为绿色:

由于JavaScript在客户端中运行,因此无需运行window.location.reload。

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <p id="varColor">green</p>

  <script>
    window.onload
    var color = "white"
    if (id.lightSwitch == true) {
      var color = "white";
    }
    if (id.lightSwitch == false) {
      var color = "black";
    }

    color = document.getElementById("varColor").innerHTML;
    document.body.style.backgroundColor = color;
  </script>

  <title>Link catalog</title>
  <style>
    body {
      background-color: __VARIABLE HERE__;
    }
  </style>
</head>

答案 3 :(得分:-1)

您可以使用: document.getElementsByTagName(“ BODY”)[0] .style.backgroundColor = color;