<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>事件入门</title>
<style>
div {
width: 50px;
height: 50px;
background-color: lightblue;
}
</style>
</head>
<body>
<button>按钮1</button>
<hr>
<div onmouseover="enter(this)" onmouseout="outer(this)">DIV1</div>
<hr>
<div>DIV2</div>
<hr>
<button>按钮2</button>
</body>
<script>
// 事件: JavaScript 与 HTML 之间交互的工具
// 事件主体: 用户, 浏览器
// 事件函数: 事件执行的动作
// 事件目标: 页面或页面中的元素
// 事件主体
var btn1 = document.querySelector('button');
// 事件调用主体是: 浏览器
window.onload = function (ev) {
console.log('页面加载完成');
};
// 事件调用主体是用户
btn1.onclick = function (ev) {
console.log('你点击了我');
};
// 添加事件
// 1. 直接以标签属性的方式添加到页面元素上
function enter(ele) {
// 设置样式
ele.style.width = '100px';
ele.style.height = '100px';
ele.style.backgroundColor = 'red';
}
function outer(ele) {
// 还原样式
ele.style.width = '50px';
ele.style.height = '50px';
ele.style.backgroundColor = 'lightblue';
}
// 除了将事件函数直接写到元素属性中, 还可以将这个事件属性单独写到JS脚本中
var div2 = document.querySelector('div:nth-of-type(2)');
div2.onmouseover = function () {
// 设置样式
this.style.width = '100px';
this.style.height = '100px';
this.style.backgroundColor = 'red';
};
div2.onmouseout = function () {
// 还原样式
this.style.width = '50px';
this.style.height = '50px';
this.style.backgroundColor = 'lightblue';
};
// 如果要删除事件, 很简单,直接将该事件属性置空即可
div2.onmouseover = null;
div2.onmouseout = null;
// 按照现代web开发要求, html定义页面结构与内容, css定义元素的样式, jS定义元素行为
// 将函数与html元素中的一个属性绑定, 并不符合html,css,javascript相互分离的原则
var btn2 = document.querySelector('button:nth-of-type(2)');
// addEventListener(事件类型, 事件函数, 执行阶段)
// 事件类型: 去掉'on'的事件属性名称
// 事件函数: 如果不需要手工移除的事件, 可以用匿名函数,否则就必须要用命名函数
// 事件的执行阶段: 布尔值, false: 冒泡阶段(微软,谷歌), true: 捕获阶段(火狐)
// btn2.addEventListener('click', function (evt) { console.log(evt.type); }, false);
// 使用addEventListener()添加的事件处理程序, 必须使用: removeEventListener()来移除
// btn2.onclick = null; // 无效
// removeEventListener()参数必须与addEventListener()完全一致
// 看上去似乎完全一致, 为什么会移除失败? 因为事件函数使用了匿名函数, 该函数定义在不同的对象中,this完全不同
// btn2.removeEventListener('click',function (evt) { console.log(evt.type); }, false);
// 将事件函数从事件处理方法中剥离
function handle(evt) {
console.log(evt.type);
}
btn2.addEventListener('click', handle, false);
btn2.removeEventListener('click', handle, false);
</script>
</html>点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号