首页 > 技术文章 > 很久以前的浮动广告(碰撞运动)

gxywb 2019-01-09 14:36 原文

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            #div1{
                width: 100px;
                height: 100px;
                background: red;
                position: absolute;
                left: 0;
                top: 0;
            }
        </style>
        <script>
            window.onload=function(){
                var oDiv=document.getElementById("div1");
                var iSpeedX=10;
                var iSpeedY=10;
                startMove();
                function startMove(){
                    setInterval(function(){
                        var L=oDiv.offsetLeft+iSpeedX;
                        var T=oDiv.offsetTop+iSpeedY;
                        if(T>document.documentElement.clientHeight-oDiv.offsetTop){
                            T=document.documentElement.clientHeight-oDiv.offsetTop;
                            iSpeedY*=-1;
                        }else if(T<0){
                            T=0;
                            iSpeedY*=-1;
                        }
                        if(L>document.documentElement.clientWidth-oDiv.offsetWidth){
                            L=document.documentElement.clientWidth-oDiv.offsetWidth;
                            iSpeedX*=-1;
                        }else if(L<0){
                            L=0;
                            iSpeedX*=-1;
                        }
                        oDiv.style.left=L+"px";
                        oDiv.style.top=T+"px";
                    },30)
                }
            }
        </script>
    </head>
    <body>
        <div id="div1"></div>
    </body>
</html>

 

推荐阅读