JS编写背景图切换

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>背景图切换</title>
    <style type="text/css">
    #wrap{
         300px;height: 225px;
        margin: 100px auto 0px;
        position: relative;
    }
    img{
        display: block;
         300px;
        height: 100%;
    }
    span{
        font-size: 30px;
    }
    #last{
        position: absolute;
        right: 40px;bottom: 5px;
    }
    #next{
        position: absolute;
        right: 5px;bottom: 5px;
    }
    </style>
</head>
<body>
    <div id="wrap">
        <img src="img/4.jpg">
        <span id="last"><</span>        
        <span id="next">></span>
    </div>
    <script type="text/javascript">
    //获取元素
    var img = document.getElementsByTagName('img')[0];
    var btn1 = document.getElementById('last');
    var btn2 = document.getElementById('next');
    //图片数组
    var images = ['img/4.jpg','img/5.jpeg','img/6.jpg','img/9.jpg'];
    //添加事件
    //定义变量用来记录当前下标
    var index= 0;
    btn1.onclick = function (){
        index++;
        if (index > 3) {
            index = 0;
        }
        //修改图片路径
        img.src = images[index];
    }
    btn2.onclick = function (){
        index--;
        if (index < 0) {
            index = 3;
        }
        //修改图片路径
        img.src = images[index];
    }

    </script>
</body>
</html>

原文地址:https://www.cnblogs.com/llz1314/p/5777567.html