我是 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)';}
最佳答案
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' 并替换为任何名称,我用按钮做了并删除了按钮标签内的 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 方法时;点击按钮颜色会改变
关于javascript - 无法在 materialize.css 中使用 javascript 更改按钮颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49681404/