jsweb2
### 事件监听:程序检测是否有事件产生,一旦有事件触发,就立即调用一个函数做出响应
1. 语法: 元素对象.addEventListener('事件类型',要执行的函数)
```html
<button class="btn">按钮</button>
<script>
const btn = document.querySelector('.btn')
btn.addEventListener('click',function(){
alert('点击l')
})
</script>
```
2. 举例:按钮广告事件
<style>
.adv{
background-color: brown;
position: relative;
top:100px;
left:500px;
text-align: center;
}
img{
width: 500px;
}
#close{
width: 20px;
height: 20px;
background-color: white;
position: absolute;
top:10px;
right:10px;
cursor:pointer;
}
.hide{
display: none;
}
.show{
display: inline-block;
}
</style>
<body>
<p>真传奇,和渣渣辉一起一刀999</p>
<button id="btn">马上下载</button>
<!-- 广告 -->
<div id="adv" class="adv hide">
<div id="close">X</div>
<img src="../images/slider01.jpg" alt=""><br/>
<h3>双十一跳楼大甩卖</h3>
</div>
<!-- 游戏注册 -->
<div class="register hide">
<h1>用户注册</h1>
<form action="">
输入手机号:<input type="text" name="uname"><button class="btn">提交</button>
</form>
</div>
<script>
const bt = document.querySelector('#btn')
const xx = document.querySelector('#close')
const adv = document.querySelector('.adv')
const register=document.querySelector('.register')
bt.addEventListener('click',function(){
adv.classList.remove('hide')
adv.classList.add('show')
})
xx.addEventListener('click',function(){
adv.classList.remove('show')
adv.classList.add('hide')
register.classList.remove('hide')
register.classList.add('show')
})
</script>
3. 事件类型
- 鼠标事件(鼠标触发)
- click 鼠标点击
- mouseenter 鼠标经过
- mouseleave 鼠标离开
4. 随机点名
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.suiji{
width: 300px;
height: 150px;
background-color: rgb(255, 255, 255);
margin: 0 auto;
font-size: 20px;
font-weight: bold;
/* text-align: center; */
}
h2{
text-align: center;
}
button{
width: 80px;
height: 30px;
}
.btn{
text-align: center;
}
</style>
</head>
<body>
<div class="suiji">
<h2>随机点名</h2>
<p>问题是:<span>这里显示人名</span></p>
<div class="btn">
<button id="action">开始</button>
<button id="over">结束</button>
</div>
</div>
<script>
const name=['张三','李四','王五','赵六','小七','老八','九九']
// 获取
const sp=document.querySelector('span')
const action=document.querySelector('#action')
const over=document.querySelector('#over')
let time=0
let num=0
// 点击开始按钮
action.addEventListener('click',function(){
time=setInterval(function(){
num=Math.floor(Math.random()*name.length)
sp.innerHTML=name[num]
},100)
if (name.length===1) {
action.disabled=true
over.disabled=true
}
})
// 点击结束按钮
over.addEventListener('click',function(){
clearInterval(time)
name.splice(num,1)
// console.log(name) 打印删除后的名单数组
})
</script>
</body>
</html>