原生js颗粒页换图效果

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>颗粒翻转</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            list-style: none;
        }
        div{
            width: 700px;
            height: 400px;
            background: url("images/img_tabs/1.jpg");
            margin: 50px auto;
            position: relative;
        }
    </style>
    <script src="move.js"></script>
    <script>
        window.onload=function(){
            var oDiv=document.getElementById('box');
            var oInp=document.getElementById('btn1');
            var C=8; //列数
            var R=5; //行数
            var W=oDiv.offsetWidth/C;  //每个span的宽度
            var H=oDiv.offsetHeight/R; //每个span的高度
            //创建span
            for(var i=0;i<R;i++){       //循环所有行
                for(var j=0;j<C;j++){  //循环每一行中的每一个
                    var oSpan=document.createElement('span');
                    oSpan.style.width=W+'px';
                    oSpan.style.height=H+'px';
                    oSpan.style.position='absolute';
                    oSpan.style.top=i*H+'px';
                    oSpan.style.left=j*W+'px';
                    oSpan.style.backgroundImage='url("images/img_tabs/0.jpg")';
                    oSpan.style.backgroundPosition=-j*W+'px -'+i*H+'px';
                    oSpan.c=j;
                    oSpan.r=i;
                    oDiv.appendChild(oSpan);
                }
            }

            var iNow=0;
            oInp.onclick=function() {
                iNow++;
                var aSpan = oDiv.children;

                if(iNow%3==0){
                        oDiv.style.backgroundImage='url("images/img_tabs/2.jpg")';
                    }else{
                        oDiv.style.backgroundImage='url("images/img_tabs/'+(iNow%3-1)+'.jpg")';
                }
                for(var i=0;i<aSpan.length;i++){
                    (function(index){
                        setTimeout(function(){
                            aSpan[index].style.backgroundImage='url("images/img_tabs/'+iNow%3+'.jpg")';
                            aSpan[index].style.opacity=0;
                            move(aSpan[index],{'opacity':1});
                        },(aSpan[index].c+aSpan[index].r)*200);
                    })(i);
                }
            }
        };
    </script>
</head>
<body>
    <input type="button" value="换图" id="btn1"/>
    <div id="box">

    </div>
</body>
</html>

  

posted @ 2016-11-09 23:16  Jason齐齐  阅读(438)  评论(0编辑  收藏  举报