实现功能
1.自动切换图片
2.点击左右按钮实现图片切换
3.点击小圆点实现图片切换
4.鼠标触碰图片时暂停自动切换效果
css代码
#wrap {
position: relative;
}
.btnAll {
position: absolute;
width: 600px;
height: 30px;
top: 170px;
text-align: center;
font-size: 30px;
}
.btn:hover{
cursor : pointer;
background: rgba(230, 31, 31, 0.28);
}
.left_btn {
position: absolute;
width: 50px;
height: 30px;
background: rgb(228, 94, 94, 0.28);
}
.right_btn {
position: absolute;
width: 50px;
height: 30px;
right: 0px;
background: rgb(228, 94, 94, 0.28);
font-size: 30px;
}
.dotAll {
position: absolute;
width: 600px;
height: 30px;
top: 310px;
background: #00000047;
}
.dot_box {
position: absolute;
width: 100px;
height: 20px;
border-radius: 30px;
top: 5px;
left: 270px;
}
.dot {
float: left;
width: 12px;
height: 12px;
border-radius: 12px;
background: #008b8b47;
margin: 3px 4px;
}
.dotNow {
background-color: rgb(29, 85, 85);
}
html代码
<div id="wrap">
<img src="./img/cat.jpeg" width="600px" id="Img" height="350px" class="left">
<div class="btnAll">
<div class="left_btn btn" onclick="backFun()"><</div>
<div class="right_btn btn" onclick="forwardFun()">></div>
</div>
<div class="dotAll">
<div class="dot_box">
<i class="dot dotNow"></i>
<i class="dot"></i>
<i class="dot"></i>
<i class="dot"></i>
<i class="dot"></i>
</div>
</div>
</div>
js代码
<script>
let arr = ["cat", "dears", "rain", "sunny", "timg"];
let current = 0;
let Img = document.getElementsByTagName('img');
let dot = document.getElementsByTagName("i");
let photo = document.getElementById('Img');
function backFun() {
current = current == 0 ? 4 : current - 1;
animationFun(current);
}
function forwardFun() {
current = (current + 1) % 5;;
animationFun(current);
}
let ziDong = setInterval(forwardFun, 1500);
Img[0].onmouseenter = function (){
clearInterval(ziDong);
}
Img[0].onmouseleave = function (){
ziDong = setInterval(forwardFun, 1500)
}
// 动画效果
function animationFun(current) {
Img[0].src = "./img/" + arr[current] + ".jpeg";
for (let i = 0; i<dot.length ; i++) {
dot[i].classList.remove('dotNow');
}
dot[current].classList.add('dotNow');
}
// 为小圆点添加点击事件
for (let i = 0; i<dot.length ; i++) {
dot[i].onclick = function() {
current = i;
animationFun(i);
}
}
</script>