【自动切换图片-添加鼠标进入和离开的效果】:
<style>
* {
padding: 0;
margin: 0;
}
div {
width: 700px;
height: 320px;
margin: 100px auto;
position: relative;
}
p {
position: absolute;
left: 0;
bottom: 0;
line-height: 50px;
background-color: #666;
color: #fff;
width: 100%;
padding-left: 10px;
font-size: 20px;
box-sizing: border-box;
}
</style>
</head>
<body>
<div>
<img src="./images/b01.jpg" alt="" />
<p>第1张图片</p>
</div>
<script>
let img = document.querySelector('img'),
div = document.querySelector('div'),
p = document.querySelector('p'),
timeId,
i = 1//第一张开始
function startTime() {
clearInterval(timeId)//避免多次点击出现倒计时加速bug(清除定时器)
timeId = setInterval(function () {
i++
if (i > 9) {//9张图片
i = 1
}
p.innerText = `第${i}张图片`//插入数据
img.src = `./images/b0${i}.jpg`
}, 1000)
}//封装函数
startTime()//设置是否自动倒计时
div.addEventListener('mouseenter', function () {
clearInterval(timeId)
}) //鼠标进入停止
div.addEventListener('mouseleave', function () {
startTime()
})//鼠标离开开始
</script>
</body>