版本一(行內(nèi)式寫法)
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是這個按鈕的內(nèi)容
- onclick是點擊址貌,點擊后會執(zhí)行后面的代碼
- style是樣式, background是背景
版本二(函數(shù)式寫法)
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 意思是聲明一個變量,相當于給按鈕起個名字存起來
- 我們把要執(zhí)行的代碼放在function中存起來
- 當我們點擊這個按鈕的時候,才會執(zhí)行function中的代碼