<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>DOM0级事件</title>
<!--
DOM0级事件:首先获取HTML元素对象,然后在script中给dom设置事件
ele.事件=代码a;在元素ele中绑定事件,触发事件后执行代码a
别让HTML把script的活给抢了
tips:
1)script中使用事件来调用函数时,不能带上函数的括号();如果带上(),在刷新页面时会直接执行函数,而不是通过事件来触发函数
-->
<style>
.inp{background: green;}
#di{
width: 100px;
height: 30px;
margin-top: 10px;
border-radius: 5px/5px;
text-align: center;
line-height: 30px;
}
.div1{background: yellow;}
.div2{background: grey;}
</style>
</head>
<body>
<input class="inp" type="button" value="锁定" />
<div id="di" class="div1">锁定</div>
<script>
//input
var a=document.getElementsByClassName("inp")[0];//获取按钮
a.onclick=function (){ //设置DOM0级事件:点击按钮后执行匿名函数
if (this.getAttribute("value")=="锁定"){ //如果按钮value="锁定"
this.setAttribute("value","解锁"); //则执行value="解锁"
this.style.background="gray"; //且按钮背景颜色变成灰色
}else{ //否则
this.setAttribute("value","锁定"); //执行value="锁定"
this.style.background="green"; //且按钮背景颜色变成绿色
}
}
//div
var div=document.getElementById("di");
div.onclick=ck; //调用ck函数,不加();如果加()刷新页面会直接执行函数ck
function ck(){
if (this.innerHTML=="锁定"){//如果this=div中内容为“锁定”
this.innerHTML="解锁";//则将内容改为“解锁”
this.className="div2";//且类名改为“this2”
}else{ //否则
this.innerHTML="锁定";//将内容改为“锁定”
this.className="div1";//且类名改为“div1”
}
}
</script>
</body>
</html>