如何写好JavaScript
各司其职
- HTML,结构
- CSS,表现
- JavaScript,行为
例子
页面切换黑 & 白两个模式
不好的模式:用JS操作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;
}
<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>
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 = '';
}
}
改进:给标签添加class,用js切换class的状态
CSS:
html,body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
#main {
position: relative;
padding: 20px;
width: 100%;
height: 100%