按钮功能
点击一个按钮后,按钮颜色改变,同时触发点击事件
按钮
<button type="button" class="colorchange" onclick="gr('.changeX','.changeY');">Windows</button>
<button type="button" class="colorchange" onclick="gr('.changeY','.changeX');">macOS</button>
点击事件的JS原生代码
function gr(s1,s2){
var x = document.querySelectorAll(s1);
var y = document.querySelectorAll(s2);
var i;
for (i = 0;i < x.length;i++){
x[i].style.display = 'block';
}
for (i = 0;i < y.length;i++){
y[i].style.display = 'none';
}
}
按钮改变的JS原生代码
var lis = document.getElementsByClassName("colorchange");
for (var i = 0; i < lis.length; i++) {
lis[i].onclick = function(ind) {
return function() {
addClass(this, "active");
var sib = siblings(this);
for (var j = 0; j < sib.length; j++) {
removeClass(sib[j], "active");
}
}
}(i)
}
//样式函数
function addClass(obj, name) {
obj.className = obj.className + " " + name;
}
//获取其他按钮
function siblings(obj) {
var sibArr = obj.parentNode.children;
var sibNewArr = [];
for (var i = 0; i < sibArr.length; i++) {
if (sibArr[i] != obj) {
sibNewArr.push(sibArr[i]);
}
}
return sibNewArr;
}
//删除样式函数
function removeClass(obj, name) {
var classStr = obj.className;
var classArr = classStr.split(" ");
var classNewArr = [];
for (var i = 0; i < classArr.length; i++) {
if (classArr[i] != name) {
classNewArr.push(classArr[i]);
}
}
obj.className = classNewArr.join(" ");