使用materialize.css中的javascript无法在点击时更改按钮颜色

时间:2018-04-05 20:57:29

标签: javascript html css materialize

我是materialize.css的新手,我实际上想要使用javascript更改按钮颜色。按钮上的每个按钮必须根据按钮内容产生不同的颜色。但是,当我点击他的按钮时,它不会改变它的颜色。

  <div class=" buttons  row center-align">
<button class="btn col s12 m6 deep-purple darken-4 center-align" id='button0'  onclick ="answer('0')" style ="display:none"><span class=" flow-text white-text text-darken-2" id="option0"></span></button><br>  
<button class="btn col s12 m6 deep-purple darken-4 center-align" id='button1'  onclick ="answer('1')" style ="display:none"><span class=" flow-text white-text text-darken-2" id="option1"></span></button><br>
<button class="btn col s12 m6 deep-purple darken-4 center-align" id='button2'  onclick ="answer('2')" style ="display:none"><span class=" flow-text white-text text-darken-2" id="option2"></span></button><br>
<button class="btn col s12 m6 deep-purple darken-4 center-align" id='button3'  onclick ="answer('3')" style ="display:none"><span class=" flow-text white-text text-darken-2" id="option3"></span></button><br>
 </div>

的javascript

 function answer(ans){
  var z = document.getElementById('option'+ans);
  var choice = z.innerHTML;
  var b = document.getElementById('button'+ans);
     if(choice == questions[x].answer){
       b.style.backgroundColor = '#008000'; 
       b.style.color = 'rgb(255, 255, 255)';}
     else{
       b.style.backgroundColor = '#700000';
       b.style.color = 'rgb(255, 255, 255)';}

1 个答案:

答案 0 :(得分:2)

HTML

<div class=" buttons  row center-align">
<button class="button col s12 m6  center-align" id='button0'  onclick ="answer('0')" style ="display:none"><span class=" flow-text white-text text-darken-2" id="option0"></span></button><br>  
<button class="button col s12 m6  center-align" id='button1'  onclick ="answer('1')" style ="display:none"><span class=" flow-text white-text text-darken-2" id="option1"></span></button><br>
<button class="button col s12 m6  center-align" id='button2'  onclick ="answer('2')" style ="display:none"><span class=" flow-text white-text text-darken-2" id="option2"></span></button><br>
<button class="button col s12 m6  center-align" id='button3'  onclick ="answer('3')" style ="display:none"><span class=" flow-text white-text text-darken-2" id="option3"></span></button><br>

只需删除materializecss按钮类'btn'并替换为任何名称,我使用按钮并删除buttons标签内的materializecss颜色类,因此最后每个按钮都是类:

 'button col s12 m6  center-align' 

并在这个html文件的自创css文件中;(main.css)

.button.col.s12.m6.center-align{
   background-color: #311b92;
padding: 10px 20px 10px;
border-radius: 50px;
font-size: 2em;}

现在当我们应用问题中提到的上述javascript方法时;按钮颜色将在点击

时更改