单击事件:
点击div换背景色
<style type="text/css"> .a{ width:200px; height:200px; background-color:#0FF; margin:5px;float:left;} </style>
<body> <div class="a" onclick="huan(this)"></div> <div class="a" onclick="huan(this)"></div> <div class="a" onclick="huan(this)"></div> <div class="a" onclick="huan(this)"></div> </body>
<script type="text/javascript">
function huan(a){
a.style.backgroundColor = "#F00";
}
</script>
点击恢复:
<script type="text/javascript">
function huan(a){
//全部恢复颜色
var d = document.getElementsByClassName("a");
//让当前点击改变颜色
for(var i=0;i<d.length;i++){
d[i].style.backgroundColor = "#0FF"
}
a.style.backgroundColor = "#F00";
}
</script>
function(){}匿名函数
加事件:
方式1:
#a{ width:200px; height:200px; background-color:#0FF; margin:5px;}
<body> <div id="a" onclick="show()"></div> </body>
<script type="text/javascript"> function show(){ alert("a"); } </script>
方式2:
#a{ width:200px; height:200px; background-color:#0FF; margin:5px;}
<div id="a"></div>
var a = document.getElementById("a"); a.onclick = function(){ alert("aa"); }
浙公网安备 33010602011771号