0
点赞
收藏
分享

微信扫一扫

js实现轮播图

功能需求

用js实现轮播图

实现思路

1:准备一个HTML结构,创建一个包含多个轮播项的容器,每个轮播项包含一个图片和一个指示器

2:编写css样式,设置轮播容器样式,包括宽度、高度、溢出隐藏等

3:编写JavaScript代码,实现轮播图的切换功能,添加指示器,用于显示当前的图片和指示下一个图片的位置;实现指示器的点击事件,用于切换到对应的轮播项。

代码实现

<!--html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>轮播图</title>
</head><!--指定js和css文件路径-->
    <link rel="stylesheet" href="../css/lunbo.css">
    <script src="../js/lunbo.js"></script>
<body>
    <div id="wrapper">
        <div id="focus">
            <ul>
                <li><a href="#">
                    <!--轮播图第一张默认图片-->
                    <img src="../img/01.jpg" alt="" id="pic"> 
                </a>
                <div class="nextPic" onclick="showNext()"></div>
                <div class="prePic" onclick="showPre()"></div>

            </li>
            </ul>

        </div>


    </div>
</body>
</html>

/* css */
* {
margin:0;
padding: 0;
}
ui,li{
    list-style: none;
}
#wrapper{
    width: 800px;
    padding-bottom: 50px;
    margin: 0 auto;
}
#focus{
    width: 800px;
    height: 280px;
    overflow: hidden;
    /* 相对定位 */
    position: relative;
}
#focus ul{
    height: 380px;
    /* 绝对定位 */
    position: absolute;
}
#focus ul li{
    float:  left;
    width: 800px;
    height: 280px;
    overflow: hidden;
    position: relative;
    background-color: #000;
}
#focus ul li div{
    position: absolute;
    overflow: hidden;
}
#focus ul li .nextPic{
    background:url(../img/spirte.png) no-repeat right top;
    width: 45px;
    height: 100px;
    right: 0px;
    top:90px;
    background-color: #000;
    opacity: 0.5;
}
#focus ul li .prePic{
    background:url(../img/spirte.png) no-repeat left top;
    width: 45px;
    height: 100px;
    left: 0px;
    top: 90px;
    /* background-color: rgba(100,10, 50, 0.5); */
    background-color: #000; 
     opacity: 0.5;
}

//js
var arr=["../img/01.jpg","../img/02.jpg","../img/02.jpg","../img/04.jpg","../img/05.jpg",];
var index=0;
function showNext(){
    if(index<arr.length-1){
        index++;
    }else{
        index=0;
    }
    // document.getElementById 通过元素的ID特性来获取元素;数组名加下标访问图片路径
    document.getElementById("pic").src=arr[index];
}
function showPre(){
    if(index>0){
        index--;
    }else{
        // 当index>=0时,index的值是数组长度-1的下标的元素
        index=arr.length-1;
    }
    document.getElementById("pic").src=arr[index];
}


运行效果

js实现轮播图_css





举报

相关推荐

0 条评论