简易轮播器

html

css

.container-image{
            position: relative;
            display: flex;
            height: 500px;
            justify-content: center;
            align-items:center;
        }
        .container-image img{
            position: absolute;
            display: block;
            margin:auto;
            opacity: 0;
            transition: opacity 2s;
        }
        .tab{
            text-align: center;
        }
        .tab span{
            display: inline-block;
            width:10px;
            height:10px;
            background: #000;
            -webkit-border-radius:5px;
            -moz-border-radius:5px;
            border-radius:5px;
        }

js

/*
        *   轮播图  轮播图的淡入淡出效果可以通过给样式添加transition:opacity:2s;2s代表时间
        * */
        $(".tab span").css("background","red");
        //获取各个节点
        let imageList = document.getElementsByClassName("banner-img");
        imageList[0].style.opacity = 1;
        let tabList = document.getElementsByClassName("tab")[0].getElementsByTagName("span");
        let number = 0;
        for(let i = 0;i < tabList.length; i++){
            tabList[i].index = i;
            tabList[i].onclick = function () {
                //遍历所有的img元素,opacity设置为0,点击的俄元素设置为1
                console.log("this是" + this.index)
                console.log("i是" + i)
                console.log("timeId" + timeId)
                clearInterval(timeId);
                for(let j = 0;j < tabList.length;j++){
                    imageList[tabList[j].index].style.opacity = 0;
                }
                number = tabList[i].index;
                imageList[tabList[i].index].style.opacity = 1;
                timeId = setInterval(Time,3000);
            }
        }
        function Time() {
            number++;
            console.log(number)
            if(number < 3){
                for(let j = 0;j < tabList.length;j++){
                    imageList[tabList[j].index].style.opacity = 0;
                }
                imageList[number].style.opacity = 1;
                console.log("第一个" + number)
            }else{
                number = 0;
                for(let j = 0;j < tabList.length;j++){
                    imageList[tabList[j].index].style.opacity = 0;
                }
                imageList[number].style.opacity = 1;
                console.log("第二个"  + number)
            }
        }
        clearInterval(timeId);  //在调用定时器要先清除定时器,不然会让定时器一直叠加,使得轮播速度越来越快
        var timeId = setInterval(Time,3000);

微信公众号:天字一等

你可能感兴趣的:(html+css+js)