此 demo 主要是用来复习 JS 数组的方法
前端新手一枚,代码肯定有不足,欢迎大家将意见和问题提出
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<button class="btn btn-info">隐藏</button>
<button class="btn btn-danger">显示</button>
<div class="wrapper">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>
</div>
</body>
</html>
CSS
.wrapper .item {
float: left;
width: 100px;
min-height: 100px;
line-height: 100px;
border: 1px solid #000;
margin-top: 10px;
margin-right: 10px;
text-align: center;
}
.wrapper .style {
border-color: red;
}
.wrapper .hide {
display: none;
}
JS
var wrapper = document.querySelector('.wrapper'),
hide = document.querySelector('.btn-info'),
show = document.querySelector('.btn-danger');
function addClass(elem, classes) {
var className = elem.className;
elem.className = elem.className + ' ' + classes;
}
function removeClass(elem, classes) {
var classArr = elem.className.split(' '),
index = 0;
for (var i = 0, len = classArr.length; i < len; i++) {
if (classArr[i] === classes) {
index = i;
}
}
elem.className = classArr.slice(0, index).join(' ');
}
wrapper.addEventListener('click', function(e){
if (e.target.className.indexOf('style') === -1) {
addClass(e.target, 'style');
} else {
removeClass(e.target, 'style');
}
}, false);
hide.addEventListener('click', function(e){
var elemArr = document.querySelectorAll('.item');
for (var i = 0; i < elemArr.length; i++) {
if (elemArr[i].className.indexOf('style') !== -1) {
var current = elemArr[i];
addClass(current, 'hide');
}
}
}, false);
show.addEventListener('click', function(e){
var elemArr = document.querySelectorAll('.item');
for (var i = 0; i < elemArr.length; i++) {
if (elemArr[i].className.indexOf('hide') !== -1) {
var current = elemArr[i];
removeClass(current, 'hide')
}
}
}, false);