回调函数仿360开机

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        #demo{
             322px;    /*不设高,因为下面的盒子消失之后,上面的盒子立刻掉下来*/
            position: fixed;
            bottom:0;
            right:0;
        }
        span{
            position: absolute;
            top:0;
            right:0;
            30px;
            height: 20px;
            cursor: pointer;
        }
    </style>
</head>
<body>
<div id="demo">
    <span id="close"></span>  <!--盒子右上角的x号区域-->
    <div  id="shang">
        <img src="t.jpg" alt=""/>
    </div>
    <div  id="xia">
        <img src="b.jpg" alt=""/>
    </div>
</div>
</body>
</html>
<script>
     function $id(id){return document.getElementById(id);}
     var demo=$id("demo");
     var shang=$id("shang");
     var xia=$id("xia");
     var close=$id("close");  //注意:不能直接用span.onclick,因为span是div的子元素,点击span的时候,发生了事件冒泡,响应在了父元素div上,所以对onclick事件的响应元素是父元素div
     close.onclick=function () {
             run(xia,{height:0},function () {  //仿360开机:点击关闭区域时,首先下面的盒子高度变为0,之后整个大盒子宽度变成0,依次消失
                 run(demo,{0})  //这里使用了回调函数
             })
     }




    //封装运动框架基本函数(多个属性)
    function run(obj,json,fn) {
        clearInterval(obj.timer);
        obj.timer=setInterval(function () {
            var flag=true; //用来判断定时器是否停止,一定写在遍历的外面,否则一遍历就true
            for( attr in json)
            {
                var cstyle=parseInt(getStyle(obj,attr)); //获得当前属性
                var step=(json[attr]-cstyle)/10; //计算步长
                step=step>0 ? Math.ceil(step) : Math.floor(step);
                obj.style[attr]=cstyle+step+"px";

                if(cstyle!=json[attr])  //在遍历中,只要有一个属性值没到达目标位置,定时器就不能停
                {
                    flag=false;
                }
            }

            if(flag)  //遍历完了之后,flag是true,所有的值都到达目标位置了,停止定时器
            {
                clearInterval(obj.timer);
                if(fn)  //回调函数,定时器关闭之后,如果有fn,执行fn()
                {
                    fn();
                }
            }
        },30)
    }

    //返回当前样式的函数
    function getStyle(obj,attr) //返回谁的,哪个属性
    {
        if(obj.currrentStyle)
        {
            return obj.currentStyle[attr];
        }
        else{
            return  window.getComputedStyle(obj,null)[attr]; //w3c浏览器
        }
    }









</script>

  

关键代码:

        1, demo(最外面整个大盒子)的定位

   固定定位,放在页面的右下方  

   span(关闭按钮)绝对定位在demo的右上方:

#demo{
    322px;
    position : fixed;
    bottom:0;
    right:0;
}  
span{
  30px;
  height: 20px;
  position:absolute;
  top:0;
  right:0;
  cursor:pointer;
}

  2,防止冒泡,因为span(关闭按钮)的父元素是demo, 所以不能直接写 span.onclick , 这样会发生冒泡,相当于点击了父元素demo, 事件会响应在父元素上,所以应该用span的 id 绑定事件

       3,回调函数,点击关闭按钮时,首先下面的盒子 高度变成 0 ,然后整个盒子的宽度 变成 0,依次消失 (所以一开始demo 的高度不应该设置,因为下面的盒子消失之后,上面的盒子会掉下来)  回调函数写的位置:定时器结束的位置

close.onclick=function(){
    run(xia, {height:0}, function(){
        run(shang,{demo:0}
    }
}    
原文地址:https://www.cnblogs.com/shanlu0000/p/11260770.html