JavaScript的:
var acc = document.getElementsByClassName("togglebtn"),
i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function () {
this.classList.toggle("active");
}
}
HTML:
<md-button class="md-fab togglebtn"></md-button>
的CSS:
button.togglebtn:after {
background-color: white;
width: auto;
font-weight: bold;
margin-left: 5px;
border: none;
content:'';
}
button.togglebtn.active:after {
width: auto;
background-color: green;
content:'close';
font-size: 10px;
}
我只能更改文字的颜色而不能更改背景颜色。当有人点击按钮时,我试图改变颜色。 :在使用css后,但改变颜色不起作用。有人可以建议我,我做错了吗
答案 0 :(得分:3)
var acc = document.getElementsByClassName("togglebtn");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function() {
this.classList.toggle("active");
}
}
&#13;
button.togglebtn.active {
background-color: green;
color: #fff;
}
&#13;
<button class="md-fab togglebtn">hello</button>
&#13;
答案 1 :(得分:1)
当您使用AngularJS时,我建议您使用ng-class
而不是纯JavaScript:
var myApp = angular.module('myApp', []);
.active { background-color: red; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<button ng-class="{active: isActive}" ng-click="isActive =! isActive">Hello</button>
</div>
答案 2 :(得分:1)
它只是一个CSS问题,你试图设置after
的样式,但你需要设置按钮的样式,然后分开:
var acc = document.getElementsByClassName("togglebtn"),
i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function() {
this.classList.toggle("active");
}
}
&#13;
button.togglebtn:after {
content: '';
}
button.togglebtn.active:after {
content: 'close';
}
button.togglebtn {
background-color: white;
width: auto;
font-weight: bold;
margin-left: 5px;
border: none;
}
button.togglebtn.active {
width: auto;
background-color: green;
content: ' close';
font-size: 10px;
}
&#13;
<button class="md-fab togglebtn">hello</button>
&#13;
答案 3 :(得分:0)
.md-button.md-fab {
line-height: 1% !important;
min-width: 0;
border-radius: 50%;
position: fixed;
margin-left: 400px;
background-color: green;
margin-top: -7px;
}
button.togglebtn:after {
color: white;
width: auto;
margin-left: 5px;
border: none;
content:'open';
font-size: 10px;
}
button.togglebtn.active:after {
width: auto;
color: black;
content:'close';
font-size: 10px;
}
.md-button.md-fab {
background-color: black !important;
}
.md-button.md-fab.active{
background-color: yellow !important;
content: 'yellow';
color: white;
}