主讲人:月影
思考:如何写“好” JavaScript
一、各司其职
JavaScript :行为
CSS :表现
HTML:结构
尽量做到职责分离
关灯吃面:版本1
黑夜与白天的切换
HTML代码:
<div id="main">
<div class="pic">
<img src="https://p4.ssl.qhimg.com/t01e932bf06236f564f.jpg">
</div>
<div class="content">
<pre>
今天回到家,
煮了点面吃,
一边吃面一边哭,
泪水滴落在碗里,
没有开灯。
</pre>
</div>
<a id="light" href="###"> </a>
</div>
CSS部分:
html,body {
margin: 0;
padding: 20px;
width: 100%;
height: 100%;
}
#main {
position: relative;
}
.pic {
float: left;
margin-right: 20px;
}
.content {
font-weight: bold;
font-size: 1.5em;
}
a#light {
border: none;
width: 25px;
height: 25px;
border-radius: 50%;
position: absolute;
left: 10px;
top: 10px;
cursor: pointer;
background: red;
}
JS:
light.onclick = function(evt) {
if(light.style.backgroundColor !== 'green'){
document.body.style.backgroundColor = '#000';
document.body.style.color = '#fff';
light.style.backgroundColor = 'green';
}else{
document.body.style.backgroundColor = '';
document.body.style.color = '';
light.style.backgroundColor = '';
}
}
这个版本就违反了各司其职的原则
Version 2:
HTML:
<div id="main" class="light-on"> /*添加了calss*/
<div class="pic">
<img src="https://p4.ssl.qhimg.com/t01e932bf06236f564f.jpg">
</div>
<div class="content">
<pre>
今天回到家,
煮了点面吃,
一边吃面一边哭,
泪水滴落在碗里,
没有开灯。
</pre>
</div>
<a id="lightButton" href="###"> </a>
</div>
CSS:
html,body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
#main {
position: relative;
padding: 20px;
width: 100%;
height: 100%;
transition: all .5s; /*添加了过渡动画*/
}
#main.light-off { /*添加了开关灯的样式*/