自定义javascript开/关开关无法正常工作

时间:2016-04-05 23:31:03

标签: javascript html css

所以我正在尝试点击一下切换" ski"和"滑雪板"

我觉得我应该使用java,但由于某些原因没有任何反应。



function switch(a,b){
document.getElementById(a).style.display = "none";
document.getElementById(b).style.display = "";}

.switch {
  border: 1px solid black;
  background-color: rgb(220,220,220);
  padding: 2px;
  width:150px;
  height:24px;
  
}

#on {
  float:left;
  display:"";
  width: auto;
  height:20px;
  background-color: rgb(95,170,250);
}

#off {
  float:right;
  display:none;
  width: auto;
  height:20px;
  background-color: rgb(250,50,25);
}

      <div class="switch">
            <div id="on" onclick="switch(on,off)">
          Ski
            </div>
            <div id="off" onclick="switch(off,on)">
            Snowboard
            </div>
          </div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

首先出现了一些错误,你不能将switch语句用作命名函数作为javascript中的关键字。另一个错误是你作为一个变量而不是字符串传入和关闭所以我也为你改变了..尝试以下:

&#13;
&#13;
function changeState(a, b){
   document.getElementById(a).style.display = 'none';
   document.getElementById(b).style.display = 'inline-block';
}
&#13;
.switch {
  border: 1px solid black;
  background-color: rgb(220,220,220);
  padding: 2px;
  width:150px;
  height:24px;
  
}

#on {
  float:left;
  display:"";
  width: auto;
  height:20px;
  background-color: rgb(95,170,250);
}

#off {
  float:right;
  display:none;
  width: auto;
  height:20px;
  background-color: rgb(250,50,25);
}
&#13;
<div class="switch">
     <div id="on" onclick="changeState('on','off')">
        Ski
     </div>
     <div id="off" onclick="changeState('off','on')">
            Snowboard
     </div>
</div>
&#13;
&#13;
&#13;