版本一(行内式写法)
css部分
html, body {
width: 100%;
height: 100%;
}
html部分
<input type="button" value="点我变红" onclick="document.body.style.background='red'">
<input type="button" value="点我变绿" onclick="document.body.style.background='green'">
<input type="button" value="点我变蓝" onclick="document.body.style.background='blue'">
<input type="button" value="点我变白" onclick="document.body.style.background='#fff'">
<input type="button" value="点我变黑" onclick="document.body.style.background='rgb(0, 0, 0)'">
注释
- input是一个标签,type="button"指它是一个按钮, value是这个按钮的内容
- onclick是点击,点击后会执行后面的代码
- style是样式, background是背景
版本二(函数式写法)
css部分
html,body {
width:100%;
height:100%;
}
HTML部分
<button id="redBtn">红色</button>
JS部分
var redBtn = document.getElementById("redBtn");
redBtn.onclick = function (){
document.body.style.background = "red"
}
注释
- var redBtn 意思是声明一个变量,相当于给按钮起个名字存起来
- 我们把要执行的代码放在function中存起来
- 当我们点击这个按钮的时候,才会执行function中的代码