DOM0级事件的绑定方法

来源:互联网 发布:妈妈讲故事软件 编辑:程序博客网 时间:2024/06/05 15:08

DOM0级事件
1、通过DOM获取HTML元素
2、(获取HTML元素)事件 = 执行脚本
语法:ele.事件=执行脚本
功能:在DOM对象上绑定事件
说明:执行脚本可以是一个匿名函数,也可以是一个函数的调用

例:
通过className来判断按钮状态:

   <style>    .btn{        width:140px; height:30px; line-height:30px;        background:yellow; color:red; font-size:14px;        text-align:center; border-radius:5px;        cursor: pointer; margin-top:30px;    }  .unlock{        width:140px; height:30px; line-height:30px;        background:purple; color:red; font-size:14px;        text-align:center; border-radius:5px;        cursor: pointer; margin-top:30px;    }  .lock{        width:140px; height:30px; line-height:30px;        background:gold; color:red; font-size:14px;        text-align:center; border-radius:5px;        cursor: pointer; margin-top:30px;    }    </style></head><body> <div class = "lock" id = "btn">锁定</div><script type="text/javascript">  //获取按钮  var btn = document.getElementById("btn");  //给按钮绑定事件,this是对该DOM元素的引用  btn.onclick = function(){    //判断如果按钮是锁定,则显示为解锁,变为灰色,否则显示为锁定,变成蓝色    if(this.className == "lock"){        this.className = "unlock";      this.innerHTML = "解锁";  }else{      this.className = "lock";      this.innerHTML = "锁定";  }}</script></body>
原创粉丝点击