如果...否则如果不能工作

时间:2018-02-22 12:02:30

标签: javascript html css logical-operators

这就是它的工作方式:改变自己 问题:       x == 0 || 1到x == 0 || x == 1 等

这是从.html

运行的
<body>   
<div class="" id="pimg1">

      </body><script>

      var x=new Date().getMonth();

     if (x == 0||x == 5||x == 2){document.getElementById('pimg1').className='pimg1';}
      else 
      if (x == 3||x == 4){document.getElementById('pimg1').className="pimg1a";}
      else 
      if (x == 6||x == 7||x == 8){document.getElementById('pimg1').className='pimg1b';}
      else                            {document.getElementById('pimg1').className='pimg1c';}


    </script></html>

外部css:

.pimg1{
   background-image: url('images/style1.jpg');/*Zone 1*/}
  .pimg1a{
 background-image: url('images/style2.jpg');/*Zone 1*/}
 .pimg1b{
background-image: url('images/style3.jpg');/*Zone 1*/}
    .pimg1c{
background-image: url('images/style4.jpg');/*Zone 1*/}

2 个答案:

答案 0 :(得分:0)

首先,将javascript代码放在<script></script>代码之间,因为javascript代码不会在html <div></div>代码中运行。

然后,使用x == 0||9||2而不是x == 0 || x == 9 || x == 2

请更改代码以便于阅读。 ||运算符在let和right侧查找条件。 9不是条件,2也不是。当您放置x == 9 || x == 2时,您说要检查左侧的条件,如果不是,请检查右侧的条件。如果一个是真的,那么我们很高兴。

答案 1 :(得分:0)

我们无法将{css用于<script>标记,也可以从<script>标记中移除<div>标记,如下所示:

<html>

<head>
  <style>
    .pimg1 {
      background-image: url('images/style1.jpg');
      /*Zone 1*/
    }
    .pimg1a {
      background-image: url('images/style2.jpg');
      /*Zone 1*/
    }
    .pimg1b {
      background-image: url('images/style3.jpg');
      /*Zone 1*/
    }
    .pimg1c {
      background-image: url('images/style4.jpg');
      /*Zone 1*/
    }
  </style>
</head>

<body>
  <div class="" id="pimg1"></div>
  <script>
    var x = new Date().getMonth();
    if (x == 0 || 9 || 2) {
      document.getElementById('pimg1').className = 'pimg1';
    } else if (x == 3 || 5) {
      document.getElementById('pimg1').className = "pimg1a";
    } else if (x == 6 || 1 || 8) {
      document.getElementById('pimg1').className = 'pimg1b';
    } else {
      document.getElementById('pimg1').className = 'pimg1c';
    }
  </script>
</body>

</html>