<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
#box {
width: 300px;
height: 150px;
position: relative;
margin: 0 auto;
overflow: hidden;
}
#box:hover {
cursor: pointer;
}
.pic, #left, #right {
position: absolute;
}
.pic {
display: none;
height: 150px;
}
#left, #right {
height: 60px;
background: #cccccc;
opacity: 0.6;
line-height: 60px;
width: 40px;
text-align: center;
top: 0;
left: 0;
bottom: 0;
right: 0;
display: none;
transition: all 500ms;
}
#right {
margin: auto 0 auto auto;
}
#left {
margin: auto auto auto 0;
}
#box:hover #right, #box:hover #left {
display: block;
cursor: pointer;
}
#right:hover, #left:hover {
background-color: white;
color: red;
opacity: 1;
}
</style>
<script>
//图片数组,左点击按钮,右点击按钮,数组下标
let pic, left, right, index = 0;
window.onload = function () {
pic = document.getElementsByClassName("pic");
left = document.getElementById("left");
right = document.getElementById("right");
//首次要第一张图显示
pic[0].style.display = "block";
//左点击效果
left.onclick = () => {
pic[index].style.zIndex = "1";
let temp = index;
index--;
if (index === -1) {
index = pic.length - 1;
}
pic[index].style.display = "block";
let opy = 1, len = 0, w = 300;
let num = setInterval(() => {
opy -= 0.01;
len--;
pic[temp].style.opacity = opy;
pic[temp].style.transform = "translateX(" + len + "px) ";
if (opy <= 0) {
clearInterval(num);
pic[temp].style.zIndex = "0";
pic[temp].style.opacity = 1;
pic[temp].style.display = "none";
pic[temp].style.transform = "translate(0,0)";
}
}, 1);
};
//右点击效果
right.onclick = () => {
pic[index].style.zIndex = "1";
let temp = index;
index++;
if (index === pic.length) {
index = 0;
}
pic[index].style.display = "block";
let opy = 1, len = 0;
let num = setInterval(() => {
opy -= 0.01;
len++;
pic[temp].style.opacity = opy;
pic[temp].style.transform = "translateX(" + len + "px) ";
if (opy <= 0) {
clearInterval(num);
pic[temp].style.zIndex = "0";
pic[temp].style.opacity = 1;
pic[temp].style.display = "none";
pic[temp].style.transform = "translate(0,0)";
}
}, 1);
};
};
</script>
<div id="left">left</div>
<div id="right">right</div>
原生js轮播图 淡入淡出
最新推荐文章于 2024-06-17 15:29:34 发布