一、步骤
- 页面布局(html):
- 这是一个简单的复选框(panel),它分为三部分:复选框的标题(panel_header)+复选框内容(panel_content)+复选框底部的全选、反选等按钮(panel_footer)。
- Checkbox 对象代表一个表单中的 一个选择框。复选框的基本构成就是Checkbox对象,每出现一次
<input type="checkbox">
Checkbox对象就会被创建一次。 - 在这种分块明显的布局中,用
<section></section>
标签较好。<hr>
显示为一条水平线,有分界作用。
<div id="panel">
<section class="panel_header">
<h2>最受欢迎的物品</h2>
<hr>
</section>
<!-- 复选框 <input type="checkbox">-->
<section class="panel_content">
<input type="checkbox">物品1<br>
<input type="checkbox">物品2<br>
<input type="checkbox">物品3<br>
<input type="checkbox">物品4<br>
<input type="checkbox">物品5<br>
<input type="checkbox">物品6<br>
<input type="checkbox">物品7<br>
<input type="checkbox">物品8<br>
<input type="checkbox">物品9<br>
</section>
<section class="panel_footer">
<hr>
<button id="allSelect">全选</button>
<button id="cancelSelect">取消选中</button>
<button id="reverseSelect">反选</button>
</section>
</div>
- 样式(ccs):
<style>
*{
margin: 0;
padding: 0;
list-style: none;
}
#panel{
width: 400px;
box-shadow: 0 0 10px #000;//box-shadow 向框添加一个或多个阴影。
margin: 100px auto;
padding: 20px;
}
.panel_header{
text-align: center;
margin-bottom: 10px;
}
.panel_footer{
text-align: center;
margin-top: 10px;
}
</style>
- JS:
- 有关事件的JS步骤大致如下:
①获取事件源及相关元素。
②绑定事件
③事件的驱动程序 - 在获取botton的过程中都是通过id来获取的,故此可将
document.getElementById()
封装起来,减少代码的一个重复量(注意要判断一下传入id的类型)。 - checked 属性 与
<input type="checkbox">
配合使用,true表示勾选,false表示取消勾选。
<script>
window.onload = function () {
// 1. 获取所有的复选框
var inputs = document.querySelectorAll('input');
// 2. 全选
$("allSelect").onclick = function () {
for(var i=0; i<inputs.length; i++){
inputs[i].checked = true;
}
};
// 3. 取消选中
$("cancelSelect").onclick = function () {
for(var i=0; i<inputs.length; i++){
inputs[i].checked = false;
}
};
// 4. 反选
$("reverseSelect").onclick = function () {
for(var i=0; i<inputs.length; i++){
inputs[i].checked = !inputs[i].checked;
}
};
//封装
function $(id) {
return typeof id === "string" ? document.getElementById(id) : null;
}
}
</script>
- 实现截图
二、个人情况
①对html中一些基本的标签不熟悉,除 <div>
、 <a>
等一些常用的标签外,忽视了其他标签的积累。
②没有方法封装的意识( function $(id)
),自己在做的时候,以及之前其他的JS方面获取元素是getElement写了一遍又一遍,出现大量重复性。