首页 > 代码库 > 原生js实现三个div层动态交换位置

原生js实现三个div层动态交换位置

html代码部分

<!--触发变换按钮-->
<input type="button" onclick="startMove()" value="点击"/>

<!--主体部分-->
<div class="localbox">
    <div id="b1" class="block1"></div>
    <div id="b2" class="block2"></div>
    <div id="b3" class="block3"></div>
</div>

 

样式部分

/*<style type="text/css">*/
.localbox{width:970px;margin:0 auto;height:600px;position:relative;}
.block1{
width:610px;
height:600px;
background-color:#ffcccc;
position:absolute;
top:0;
left:0;
z-index:2;
}
.block2{
width:360px;
height:300px;
position:absolute;
background-color:#ccffcc;
top:0;
left:610px;
z-index:1;
}
.block3{
width:360px;
height:300px;
position:absolute;
background-color:#ccccff;
top:300px;
left:610px;
z-index:0;
}
/*</style>*/

 

 

js部分

/*<script type="text/javascript">*/
var timer1=null;
var timer2=null;
var timer3=null;
var b1,b2,b3;
var i=0;
var box=new Array(3);
box[0]=document.getElementById(‘b1‘);
box[1]=document.getElementById(‘b2‘);
box[2]=document.getElementById(‘b3‘);

function startMove(){
    for(i=0;i<3;++i){
        if(box[i].offsetLeft==0&&box[i].offsetTop==0){
            b1=box[i];
        }
        if(box[i].offsetLeft==610&&box[i].offsetTop==0){
            b2=box[i];
        }
        if(box[i].offsetLeft==610&&box[i].offsetTop==300){
            b3=box[i];
        }
    }
    timer1=setInterval(function(){
        if(b1.offsetLeft>=610){
            clearInterval(timer1);
        }else{
            b1.style.height=b1.offsetHeight-30+‘px‘;
            b1.style.width=b1.offsetWidth-25+‘px‘;
            b1.style.left=b1.offsetLeft+61+‘px‘;
        }
    },125);
    timer2=setInterval(function(){
        if(b2.offsetTop>=300){
            clearInterval(timer2);
        }else{
            b2.style.top=b2.offsetTop+30+‘px‘;
        }
    },125);
    timer3=setInterval(function(){
        if(b3.offsetLeft<=0){
            clearInterval(timer3);
        }else{
            b3.style.left=b3.offsetLeft-61+‘px‘;
            b3.style.top=b3.offsetTop-30+‘px‘;
            b3.style.width=b3.offsetWidth+25+‘px‘;
            b3.style.height=b3.offsetHeight+30+‘px‘;
        }
    },125);
    }
/*</script>*/