<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
div{width: 150px;height: 150px;background: skyblue;margin-top: 50px;}
</style>
<!-- JS与HTML的交互都是通过事件来完成的
在JS中,所有的事件都需要加on前缀 on-事件名
事件分为三类:
1.传统事件绑定
2.脚本模型
3.W3C事件
事件三要素:
1.事件对象(事件的触发者、绑定对象)
2.事件名称
3.事件处理函数
注意:事件需要触发,才能执行 -->
</head>
<body>
<!-- 第一个例子 -->
<!-- <button οnclick="change(30)">旋转30度</button>
<button οnclick="change(50)">旋转50度</button>
<div id="box"></div> -->
<!-- 第二个例子 -->
<!-- <button id="btn">点我</button> -->
<!-- 第三个例子 -->
<button id="btn">点我</button>
<button id="btn-remove">移除按钮一的事件</button>
<script type='text/javascript'>
//1.
// 传统事件绑定
// 将事件以属性的形式添加到HTML元素标签中
/*
优点:简单、易用
缺点:将js代码插入到了HTML中,不利于多人协作开发
*/
// function change(degree){
// //旋转div30度
// var o=document.getElementById('box');
// // var ts=o.style.transform;
// // console.log(ts);
// o.style.transform='rotate('+degree+'deg)';
// // degree+=30;
// }
/*2.
脚本模型:在JS里完成事件的绑定
节点对象.on-事件名称=事件处理函数;
*/
// var b=document.getElementById('btn');
// b.οnclick=function(){
// alert('run');
// };
// //添加鼠标事件
// b.οnmοuseοver=function(){
// this.style.background='green';
// };
//3.
// W3C事件
/*
用函数实现事件的绑定
addEventListener(事件名称,事件处理函数,false) 添加事件
removeEventListener(事件名称,事件处理函数,false) 移除事件
*/
var btn=document.getElementById('btn');
var btnRemove=document.getElementById('btn-remove');
//添加事件
btn.addEventListener('click',function(){
alert('hello');
},false);
btn.addEventListener('mouseover',show,false);
//添加移除按钮一的事件
btnRemove.addEventListener('click',function(){
//移除按钮一的mouseover事件
btn.removeEventListener('mouseover',show,false);
},false);
function show(){
console.log('over');
}
</script>
</body>
</html>