代码-JS之淡入淡出背景自动切换

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        *{
            padding:0;
            margin:0;
        }
        div{
            width:600px;
            height:400px;
            margin:10px auto;
            position: relative;
        }
        img{
            /*子绝父相*/
            position: absolute;
            z-index: 1;
        }
        img:first-child{
            z-index: 3;
        }
    </style>
</head>
<body>

<div>
    <img src="images/1.jpg" alt="">
    <img src="images/2.jpg" alt="">
    <img src="images/3.jpg" alt="">
    <img src="images/4.jpg" alt="">
    <img src="images/5.jpg" alt="">
    <img src="images/6.jpg" alt="">
</div>

<script>
    //获取img
    var imgs = document.getElementsByTagName('img');
    //定义下标
    var nowIndex = 0;
    var nextIndex = 1;

    //绑定定时器
    setInterval(function () {
        if(nowIndex > 5){
            nowIndex = 0;
        }
        //next先一步大于五先执行,实现循环
        if(nextIndex > 5){
            nextIndex =0;
        }
        //循环更改层级
        imgs[nowIndex].style.zIndex=2;
        imgs[nextIndex].style.zIndex=3;
        //渐变
        change(imgs[nextIndex]);
        //下标自增
        nowIndex++;
        nextIndex++;
    },2000);

    //定义函数实现淡入淡出
    function change(element) {

        setOpacity(element, 0);

        for(var i=0; i<=50; i++){
            (function (x) {
                setTimeout(function () {
                    setOpacity(element, 1/50*x);
                    if( x==50){
                        imgs[nowIndex-1].style.zIndex=1;
                    }
                },10*x);
            })(i);
        }
    }

    //函数,设置元素的透明度
    function setOpacity(ele, val){
        if(ele.filters){
            ele.style.filter = "alpha(opacity=" + val*100 + ")";
        }else{
            ele.style.opacity = val;
        }
    }
</script>
</body>
</html>