什么是事件?
事件是在编程时系统内发生的动作或者发生的事情
比如用户在网页上单击一个按钮
什么是事件监听?
就是让程序检测是否有事件产生,一旦有事件触发,就立即调用一个函数做出响应,也称为绑定事件或者注册事件。比如鼠标经过显示下拉菜单,比如点击可以播放轮播图等等。
元素对象.addEventListener('事件类型',要执行的函数)
事件监听三要素:
- <button>点击button>
- <script>
- // 需求:点击了按钮,弹出一个对话框
- // 1. 事件源 按钮
- const btn = document.querySelector('button')
- btn.addEventListener('click',function(){
- alert('今天吃什么?')
- })
- // 2. 事件类型 点击鼠标
- // 3. 事件处理程序 弹出对话框
- script>

鼠标经过,与鼠标离开
- DOCTYPE html>
-
-
-
Document -
- div {
- width: 200px;
- height: 200px;
- background-color: blue;
- }
-
-
-
- const div = document.querySelector('div')
- // 鼠标经过
- div.addEventListener('mouseenter',function(){
- console.log('我到了')
- })
- // 鼠标离开
- div.addEventListener('mouseleave',function(){
- console.log('我走了')
- })
-
京东点击关闭顶部广告
需求:点击关闭之后,顶部关闭
- DOCTYPE html>
-
-
-
-
-
Document -
- .box {
- position: relative;
- width: 1000px;
- height: 200px;
- background-color: pink;
- margin: 100px auto;
- text-align: center;
- font-size: 50px;
- line-height: 200px;
- font-weight: 700;
- }
-
- .box1 {
- position: absolute;
- right: 20px;
- top: 10px;
- width: 20px;
- height: 20px;
- background-color: skyblue;
- text-align: center;
- line-height: 20px;
- font-size: 16px;
- cursor: pointer;
- }
-
-
-
- 我是广告
- X
-
-
- // 1. 获取事件源
- const box1 = document.querySelector('.box1')
- // 关闭的是大盒子
- const box = document.querySelector('.box')
- // 2. 事件侦听
- box1.addEventListener('click', function () {
- box.style.display = 'none'
- })
-
-
DOM L0
事件源.on事件 = function(){}
DOM L2
事件源.addEventListener(事件,事件处理函数)
区别:on方式会被覆盖,addEventListener方式可以多次绑定,拥有事件更多特性
发展史:

分析:
- 点击开始按钮随机抽取数组的一个数据,放到页面中
- 点击结束按钮删除数组当前抽取的一个数据
- 当抽取到最后一个数据的时候,两个按钮同时禁用(写点开始里面,只剩最后一个数据不用抽了)
核心:利用定时器快速展示,停止定时器结束展示
-
- DOCTYPE html>
-
-
-
-
Document -
- * {
- margin: 0;
- padding: 0;
- }
-
- h2 {
- text-align: center;
- }
-
- .box {
- width: 600px;
- margin: 50px auto;
- display: flex;
- font-size: 25px;
- line-height: 40px;
- }
-
- .qs {
-
- width: 450px;
- height: 40px;
- color: red;
-
- }
-
- .btns {
- text-align: center;
- }
-
- .btns button {
- width: 120px;
- height: 35px;
- margin: 0 50px;
- }
-
-
-
随机点名
-
- 名字是:
- 这里显示姓名
-
-
-
-
-
-
-
- // 数据数组
- const arr = ['马超', '黄忠', '赵云', '关羽', '张飞']
- // 定时器的全局变量
- let timerId = 0
- // 随机号要全局变量
- let random = 0
- // 业务1. 开始按钮模块
- const qs = document.querySelector('.qs')
- // 1.1 获取开始按钮对象
- const start = document.querySelector('.start')
- // 1.2 添加点击事件
- start.addEventListener('click',function(){
- timerId = setInterval(function(){
- // 随机数
- random = parseInt(Math.random() * arr.length)
- // console.log(arr[random]);
- qs.innerHTML = arr[random]
- },35)
-
- // 如果数组里面只有一个值了,就不需要抽取了,让两个按钮禁用就可以了
- if(arr.length === 1){
- // start.disabled = true
- // end.disabled = true
- strat.disabled = end.disabled = true
- }
-
- })
-
- // 2. 关闭按钮模块
- const end = document.querySelector('.end')
- end.addEventListener('click',function(){
- clearInterval(timerId)
- // 结束了,可以删除掉当前抽取的那个数组元素
- arr.splice(random,1)
- console.log(arr);
- })
-
-
-