练手小案例:用js实现3D轮播图

使用HTML5+CSS3+JS实现3D轮播图,绝对的干货!

代码里面有相应的注释和介绍,所以话不多说,直接展示代码!

效果图:

练手小案例:用js实现3D轮播图_第1张图片

HTML部分:

 CSS部分:

*{
    padding: 0;
    margin: 0;
}
ul,li,ol{
    list-style: none;
}
a{
    text-decoration: none; 
}
.box{
    width: 1200px;
    height: 700px;
    margin-right: auto;
    margin-left: auto;
    position: relative;
    perspective: 500px;   /* 3D虚拟视点距屏幕的距离 */
    /* background-color: purple; */
}
.box ul img{
    width: 627px;
    height: 375px;
}
.box>ul>li>a{
    display: block;
}
.box>ul>li{
    position: absolute;
    z-index: 1; /* 堆叠顺序 */
    transform: scale(0.7,0.7);
    transition:all 0.5s; /* 过度属性 很重要 */
    top: 140px;   /* 后面这两个属性也非常重要:*/
    left: 280px; /* 让图片原始位置居中 */
}
/* 当前图片 */
.box>ul>li.current{
    margin-left: 13px;
    transform:scale(1,1);
    z-index: 100;
}
/* 下一张图片 */
.box>ul>li.next{
    right: 0;
    margin-left: 300px;
    transform:scale(0.7,0.7) rotateY(-10deg);
    z-index: 50;
}
/* 上一张图片 */
.box>ul>li.prev{
    left: 0;
    margin-left: -6px;
    transform:scale(0.7,0.7) rotateY(10deg);
    z-index: 50;
}
/* 按钮 */
.prevBtn,.nextBtn{
    display: block;
    width: 50px;
    height: 90px;
    position: absolute;
    background-color: red;
    opacity: 0.5;
    top: 40%;
    transition: all 0.5s;
    z-index: 200;
}
.prevBtn{
    left:0;
}
.nextBtn{
    right:0;
}
 /* 按钮的hover 效果*/
.prevBtn:hover ,.nextBtn:hover{
    opacity: 1;
}

JavaScript部分:

let lis = document.querySelectorAll("ul > li");
let prevBtn = document.querySelector(".prevBtn");
let nextBtn = document.querySelector(".nextBtn");
let index = 0;
function showPic(n){
    let prevli,nextli;
    if(n === lis.length-1){
        nextli = 0;
    }else{
        nextli = n + 1;
    }
    if(n === 0){
        prevli = lis.length-1;
    }else{
        prevli = n - 1;
    }
    for(let i = 0; i <= lis.length-1; i++){
        lis[i].className = "";
    }
    lis[n].className = "current";
    lis[nextli].className = "next";
    lis[prevli].className = "prev";
}
showPic(index);//初始化
nextBtn.addEventListener("click",function(){
    index--;
    if(index < 0){
        index = lis.length-1;
    }
    showPic(index);
});
prevBtn.addEventListener("click",function(){
    index++;
    if(index > lis.length-1){
        index = 0;
    }
    showPic(index);
})
//自动切换
setInterval(function(){
    index--;
    if(index < 0){
        index = lis.length-1;
    }
    showPic(index);
},5000);

学会了记得点赞哦!

你可能感兴趣的:(JavaScript,javascript,css,css3,html,html5)