事件
事件是编程语言中的术语,它是用来描述程序的行为或状态的,一旦行为或状态发生改变,便立即调用一个函数。
事件监听
结合 DOM 使用事件时,需要为 DOM 对象添加事件监听,等待事件发生(触发)时,便立即调用一个函数。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>事件监听</title>
</head>
<body>
<h3>事件监听</h3>
<p id="text">为 DOM 元素添加事件监听,等待事件发生,便立即执行一个函数。</p>
<button id="btn">点击改变文字颜色</button>
<script>
// 1. 获取 button 对应的 DOM 对象
const btn = document.querySelector('#btn')
// 2. 添加事件监听
btn.addEventListener('click', function () {
console.log('等待事件被触发...')
// 改变 p 标签的文字颜色
let text = document.getElementById('text')
text.style.color = 'red'
})
// 3. 只要用户点击了按钮,事件便触发了!!!
</script>
</body>
</html>
事件类型
鼠标事件
鼠标事件是指跟鼠标操作相关的事件,如单击、双击、移动等。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>事件监听</title>
<style>
.box{
width: 100px;
height: 100px;
border: 1px solid #000;
}
</style>
</head>
<body>
<h3>鼠标事件</h3>
<p>监听与鼠标相关的操作</p>
<hr>
<div class="box"></div>
<script>
// 需要事件监听的 DOM 元素
const box = document.querySelector('.box');
// 监听鼠标是移入当前 DOM 元素
box.addEventListener('mouseenter', function () {
// 修改文本内容
this.innerText = '鼠标移入了...';
this.style.color = 'red'
// 修改光标的风格
this.style.cursor = 'move';
})
// 监听鼠标是移出当前 DOM 元素
box.addEventListener('mouseleave', function () {
// 修改文本内容
this.innerText = '鼠标移出了...';
this.style.color = 'green'
})
</script>
</body>
</html>
键盘事件
keydown 键盘按下触发
keyup 键盘抬起触发
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div{
width: 100px;
height: 100px;
border: 1px solid #000;
display: none;
}
</style>
</head>
<body>
<input type="text" name="" id="" value="">
<div></div>
<script>
//获取DOM对象
const input = document.querySelector('input')
const div = document.querySelector('div')
//监听键盘是否按下
input.addEventListener('keydown',function(){
div.style.display = 'block'
})
//监听键盘是否弹回
input.addEventListener('keyup',function(){
div.style.borderColor = 'red'
})
</script>
</body>
</html>
焦点事件
focus 获得焦点
blur 失去焦点
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" name="" id="" value="爱会消失对吗">
<script>
const input = document.querySelector('input')
//监听当前DOM是否获得焦点
input.addEventListener('focus',function(){
input.value = ''
})
//监听当前DOM是否失去焦点
input.addEventListener('blur',function(){
input.value = '爱会消失对吗'
})
</script>
</body>
</html>