原生js 实现轮播图

1.直接贴代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>轮播图</title>
    <style>
    *{
        margin: 0;
        padding: 0;
        list-style-type: none;
        text-decoration: none;
    }
    #fade{
        width: 500px;
        height: 500px;
    }
	.dom_img{
		position: absolute;
		z-index:-1
	}
    .dom_left{
        position: absolute;
		background-color: aliceblue;
		height:50px;
		width:40px;
        top: 225px;
		left:10px;
		z-index:1000;
		cursor:pointer
    }
    .dom_right{
        position: absolute;
		background-color: aliceblue;
		height:50px;
		width:40px;
        top: 225px;
        left:450px;
		z-index:1000;
		cursor:pointer
    }
    .ul_dian{
        position: absolute;
		z-index:1000;
		top:470px;
		left: 200px;
		width:100px;
		height:30px;
		display:flex;
		align-items: center;
		justify-content: space-between;
    }
 
	.dian{
		width:30px;
		height:30px
	}
    </style>
</head>
<body>
    <center><h2>轮播图</h2></center>
    <div id="fade">
        <img src="1.png" width="500px" height="500px" id="carousel" class='dom_img'>
		<img src="left.png" class='dom_left' id="left">
		<img src="right.png" class='dom_right' id="right">
        <ul class="ul_dian">
            <li><img src="dian.png" class='dian'></li>
            <li><img src="dian.png" class='dian'></li>
            <li><img src="dian.png" class='dian'></li>
        </ul>
    </div>
    <script>
        var doml = document.getElementById("carousel")
        var num=1;
        // 定时换图
        setInterval(function(){
            num++;
            if(num == 4){
                num = 1;     
            }
            doml.src=num+".png" 
        },3000)
        var left = document.getElementById("left")
        var right = document.getElementById("right")
        // 向左切换
        left.onclick=function(){
            num--;
            if(num == 0){
                num = 3;     
            }
            doml.src=num+".png" 
   
        }

        // 向右切换
        right.onclick=function(){
            num++;
            if(num == 4){
                num = 1;     
            }
            doml.src=num+".png" 
        }


        // 点击圆点换图
        var allLi = document.getElementsByTagName('ul')[0].getElementsByTagName("li");
        for(var i = 0 ; i < allLi.length ; i++){
            // 给每个li元素赋值,每循环一次,i+1;
            allLi[i].index = i;
            allLi[i].onclick=function(){
                // li的索引是从0开始的,所以要+1
                var num = this.index+1;
                doml.src=num+".png" 
            }   
        }
    </script>
</body>
</html>

问题:
1.图片切换的时候少了一点动画,看起来很生硬。
2.图片切换的时候如果与定时器的时间刚好相同,图片就会来回切换

posted @ 2021-01-04 11:41  倔强的烤马铃薯  阅读(8)  评论(0)    收藏  举报  来源