zoukankan      html  css  js  c++  java
  • 原生js实现一个DIV的碰撞反弹运动

     原生js实现一个DIV的碰撞反弹运动:

      关键在于DIV的边界检测,进而改变运动方向,即可实现碰撞反弹效果。

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            *{margin:0;}
            div{height:100px;width:100px;background:red;position:absolute;}
            /*添加绝对定位*/
    
        </style>
        <script>
            window.onload=function(){
                var btn=document.getElementById("btn");
                var div=document.getElementById("div");
                var speedx=6;
                var speedy=8;
                var t=null;
                btn.onclick=function(){
                    clearInterval(t);
                    t=setInterval(function(){
                        var l=div.offsetLeft+speedx;
                        var t=div.offsetTop+speedy;
    
                        if(l>=document.documentElement.clientWidth-div.offsetWidth){
                            speedx*=-1;
                            l=document.documentElement.clientWidth-div.offsetWidth;
                        }else if(l<=0){
                            speedx*=-1;
                            l=0;
                        }
                        if(t>=document.documentElement.clientHeight-div.offsetHeight){
                            speedy*=-1;
                            t=document.documentElement.clientHeight-div.offsetHeight;
                        }else if(t<=0){
                            speedy*=-1;
                            t=0;
                        }
                        div.style.left=l+"px";
                        div.style.top=t+"px";
                    },10);
                }
            }
        </script>
    </head>
    <body>
    <input type="button" id="btn" value="开始运动">
    <div id="div"></div>
    </body>
    </html>
  • 相关阅读:
    2015-10-09 Fri 晴 加快进度看书
    lseek()函数
    pipe()管道最基本的IPC机制
    linux VFS 内核数据结构
    tcp协议中mss的理解
    tcp的精髓:滑动窗口
    2015-10-11 Sunday 晴 ARM学习
    2015-10-12 晴 审面包车
    2015-10-14 晴 tcp/ip
    pyfits过滤数据更新文件。
  • 原文地址:https://www.cnblogs.com/mycognos/p/9240515.html
Copyright © 2011-2022 走看看