JS图片切换动画版

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
    body{
        margin: 0;
        background-color: #5e5e5e;
    }
    #box{
        width: 857px;
        height: 574px;
        padding-top: 126px;
        padding-left:143px;
        background: url(img/bg.png) no-repeat;
        margin: 0px auto;
    }
    #wrap{
        width: 700px;
        height: 420px;
    }
    #wrap div{
        width: 10px;
        height: 420px;
        background: url(img/01.png) no-repeat;
        float: left;
        transition: .5s;
    }
</style>
</head>
<body>
<div id="box">
    <div id="wrap">
    <!-- <div style="background-position-x: 0px"></div>
    <div style="background-position-x: -10px"></div>
    <div style="background-position-x: -20px"></div>
    <div style="background-position-x: -30px"></div>-->
    </div>
</div>
<script>

    window.onload = function(){
        
        // 第一步动态创建70个子div,然后利用背景图片拼出完整的图片
        var wrap = document.getElementById('wrap');
        var str = "";
        var len = 70;

        // 动态创建70个子div存在str变量中,并添加到wrap里面
        for (var i = 0; i < len; i++) {
            str += '<div style="background-position-x: '+(-10*i)+'px"></div>';
        };
        wrap.innerHTML = str;

        var divs = wrap.getElementsByTagName('div');
        var srcNum = 2;
        var timer;
        var num = 0;

        // 让第一张图子元素慢慢隐藏,第二张图子元素慢慢显示
        function tab(n){
            // 如果上一个子div存在
            if(divs[n-1]){
                divs[n-1].style.opacity = 1;
            }
            // 如果当前子div存在
            if(divs[n]){
                divs[n].style.opacity = 0;
                divs[n].style.backgroundImage ='url(img/0'+srcNum+'.png)';
            }
        };
        
        move();

        // 封装一个move函数
        function move(){
            timer = setInterval(function(){
                tab(num);
                num++;
                console.log(num);    //这里可以发现num在不停的变大,定时器没有关掉,得做判断

                if(num == 71){
                    clearInterval(timer);
                    num = 0;
                    // 这里可以看到切换到第二张图就不动了,这里就得改变图片的src
                    srcNum ++;
                    if(srcNum == 6){
                        srcNum = 1;
                    }
                }
            },70);
        };
        setTimeout(move,500);

    };
</script>
</body>
</html>

 

posted @ 2016-10-27 10:45  波克比520  阅读(657)  评论(0编辑  收藏  举报