JS应用实例2:轮播图

在学习轮播图之前,要先会切换图片:

找三张图片,命名1.jpg,2.jpg,3.jpg

示例:

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title>切换图片</title>
        <style>
            div {
                border: 1px solid white;
                width: 500px;
                height: 350px;
                margin: auto;
                text-align: center;
            }
        </style>
        <script>
            var i = 1;

            function changeImg() {
                i++;
                document.getElementById("img1").src = "./img/" + i + ".jpg";
                if(i == 3) {
                    i = 0;
                }
            }
        </script>
    </head>

    <body>
        <div>
            <input type="button" value="下一张" onclick="changeImg()" />
            <img src="./img/1.jpg" width="100%" height="100%" id="img1" />
        </div>
    </body>

</html>

上面代码是通过按钮切换图片

轮播图自动切换图片,用到onload事件

JS代码:

            function init(){
                //书写轮图片显示的定时操作
                setInterval("changeImg()",3000);
            }
            
            //函数
            var i=0
            function changeImg(){
                i++;
                //获取图片位置并设置src属性值
                document.getElementById("img1").src="./img/"+i+".jpg";
                if(i==3){
                    i=0;
                }
            }

HTML代码:

这里要注意:onload写在body标签中

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            div {
                border: 1px solid white;
                width: 500px;
                height: 350px;
                margin: auto;
                text-align: center;
            }
        </style>
        <script>
            function init(){
                //书写轮图片显示的定时操作
                window.setInterval("changeImg()",1000);
            }
            var i=0
            function changeImg(){
                i++;
                //获取图片位置并设置src属性值
                document.getElementById("img1").src="./img/"+i+".jpg";
                if(i==3){
                    i=0;
                }
            }
        </script>
    </head>

    <body onload="init()">
        <div>
            <input type="button" value="下一张" onclick="changeImg()" />
            <img src="./img/1.jpg" width="100%" height="100%" id="img1" />
        </div>
    </body>

</html>

每一秒自动切换一张图片

原文地址:https://www.cnblogs.com/xuyiqing/p/8372927.html