目标:能够给DOM元素添加事件监听
■ 什么是事件?
事件是在编程时系统内发生的动作或者发生的事情
比如用户在网页上单击一个按钮
• 什么是事件监听?
就是让程序检测是否有事件产生,一旦有事件触发,就立即调用一个函数做出响应,也称为绑定事件或者注册事件
比如鼠标经过显示下拉菜单,比如点击可以播放轮播图等等
元素对象.addEventListener('事件类型',要执行的函数')
- <style>
- .boxl {
- position: absolute;
- right: 20px;
- top: 10px;
- width: 20px;
- height: 20px;
- background-color: H skyblue;
- text-align: center;
- line-height: 20px;
- font-size: 16px;
- cursor: pointer;
- }
- style>
- <body>
- <div class="box">
- 我是广告
- <div class="boxl">Xdiv>
- div>
- <script>
- // 1.获取事件源
- const boxl = document.querySelector('.boxl')
- //关闭的是大盒子
- const box = document.querySelector('.box')
- // 2.事件侦听
- boxl.addEventListener('click', function () {
- box. style. display = 'none'
- })
- script>
- body>
- <style>
- *i margin: 0;
- padding: 0;
- text-align: center;
- }
- .box {
- width: 600px;
- margin: 50px auto;
- display: flex;
- font-size: 25px;
- line-height: 40px;
- }
- .qs {
- width: 450px;
- height: 40px;
- color: Ored;
- }
- .btns {
- text-align: center;
- }
- .btns button {
- width: 120px;
- height: 35px;
- margin: 0 50px;
- }
- style>
-
- <body>
- <h2>随机点名h2>
- <div class="box">
- <span>名字是:span>
- <div class=“qs”>这里显示姓名div>
- div>
- <div class="btns">
- <button class="start">开始button>
- <button class="end">结束<button>
- div>
-
- <script>
- //数据数组
- let timerId=0
- const random=0
- const arr = ['马超','黄忠','赵云','关羽','张飞']
- const qs = document.querySelector('.qs')
- //1.1获取开始按钮对象
- const start = document.querySelector('.start')//?????????
- //1.2添加点击事件
- start.addEventListener(* click', function () {
- timerld = setlnterval(function () {
- //随机数
- const 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
- start.disabled = end.disabled = true
- }
- })
- //2.关闭按钮模块
- const end = document.querySelector('.end')
- end.addEventListener('click', function () {
- clearInterval(timerld)
- //结束了,可以删除掉当前抽取的那个数组元素
- arr.splice(random, 1)
- console.log(arr)
- })
-
-
-
- script>
- body>
函数的垃圾回收机制