js - 點擊事件
阿新 • • 發佈:2018-01-05
href 如果 聲明 感受 gpo css 寬度 highlight enter
/*
1. 變量
2. 事件
3. 函數
4. 屬性
*/
目前,關於事件我們只學了一個點擊事件。
如果覺得前邊獲取元素時寫的document.getElement(s)..太長了,那麽可以通過聲明變量來簡化它
例如:
<script>
var box = document.getElementById(‘ box ‘)
var btn = document.getElementById(‘ btn ‘)
btn.onclick = function(){
box.style.background=" red "
}
</script>
可以看到利用js可以通過點擊其他位置控制另一個元素樣式的變化
利用這一點,我們做了一個小東西,以下是代碼:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <link rel="stylesheet" href="../css/index.css" /> </head> <body> <div id="main"> <div id="word"> <span>請為下邊的DIV設置樣式:</span> <button id="set">點擊設置</button> </div> <div id="box"></div> </div> <div id="bg"> <div id="center"> <div id="color"> <span>請選擇背景色:</span> <button id="red">紅</button> <button id="yel">黃</button> <button id="blue">藍</button> </div> <div id="width"> <span>請選擇寬度:</span> <button id="w200">200</button> <button id="w300">300</button> <button id="w400">400</button> </div> <div id="height"> <span>請選擇高度:</span> <button id="h200">200</button> <button id="h300">300</button> <button id="h400">400</button> </div> <div id="choose"> <button id="reg">恢復</button> <button id="sure">確定</button> </div> </div> </div> <script> var set = document.getElementById (‘set‘); var box = document.getElementById (‘box‘); var bg = document.getElementById (‘bg‘); var red = document.getElementById (‘red‘); var yel = document.getElementById (‘yel‘); var blue = document.getElementById (‘blue‘); var w200 = document.getElementById (‘w200‘); var w300 = document.getElementById (‘w300‘); var w400 = document.getElementById (‘w400‘); var h200 = document.getElementById (‘h200‘); var h300 = document.getElementById (‘h300‘); var h400 = document.getElementById (‘h400‘); var reg = document.getElementById (‘reg‘); var sure = document.getElementById (‘sure‘); set.onclick = function(){ bg.style.display = ‘block‘; } red.onclick = function(){ box.style.background = ‘#f50b42‘; } yel.onclick = function(){ box.style.background = ‘#f9e74f‘; } blue.onclick = function(){ box.style.background = ‘#84a8f1‘; } w200.onclick = function(){ box.style.width = ‘200px‘; } w300.onclick = function(){ box.style.width = ‘300px‘; } w400.onclick = function(){ box.style.width = ‘400px‘; } h200.onclick = function(){ box.style.height = ‘200px‘; } h300.onclick = function(){ box.style.height = ‘300px‘; } h400.onclick = function(){ box.style.height = ‘400px‘; } reg.onclick = function(){ box.style.width = ‘142px‘; box.style.height = ‘142px‘; box.style.background = ‘#fff‘; } sure.onclick = function(){ bg.style.display = ‘none‘; } </script> </body> </html>
從這裏,我初次感受到了 js 的靈活,好多東西還沒見識到,要繼續努力才是。
js - 點擊事件