zoukankan      html  css  js  c++  java
  • 运动的小球自动变键盘控制

    <!DOCTYPE html>,
    <html>
    <head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
    .box{ 400px;height: 400px;border: 1px solid black;position: relative;}
    .ball{ 30px;height: 30px;border-radius: 50%;background-color: red;position: absolute;left: 0;top: 0;}
    </style>
    </head>
    <body>
    <div class="box">
    <div class="ball">

    </div>
    </div>
    </body>
    <script type="text/javascript">
    var obox = document.querySelector(".box");
    var oball = document.querySelector(".ball");
    var a;
    var b;
    var c;
    var d;
    document.onclick = function(){

    清楚计时器,防止多次点击出现多个计时器,小球运动速度依次增加
    clearInterval(a);
    clearInterval(b);
    clearInterval(c);
    clearInterval(d);

    建立几个计时器,每当运动到大边框时清楚计时器,建立另一个计时器,换一个方向运行
    a=setInterval(function(){
    if(oball.offsetLeft>370){
    oball.offsetLeft=370;
    clearInterval(a);
    b=setInterval(function(){
    if(oball.offsetTop>370 ){
    oball.offsetTop=370;
    clearInterval(b);
    c=setInterval(function(){
    if(oball.offsetLeft<0){
    oball.offsetLeft=0;
    clearInterval(c);
    d=setInterval(function(){
    if(oball.offsetTop<0 ){
    oball.offsetTop=0
    }else{
    oball.style.top = oball.offsetTop-5+"px"
    }

    },30)
    }else{
    oball.style.left = oball.offsetLeft-5+"px"
    }

    },30)
    }else{
    oball.style.top = oball.offsetTop+5+"px"
    }

    },30)
    }else{
    oball.style.left=oball.offsetLeft+5+"px"
    }

    },30)
    }

    键盘按下时清空所有计时器,由键盘来控制
    document.onkeydown=function(eve){
    clearInterval(a);
    clearInterval(b);
    clearInterval(c);
    clearInterval(d);
    e=eve||window.event;
    if(e.keyCode==37){
    if(oball.offsetLeft<0){
    oball.offsetLeft=0
    }else{
    oball.style.left=oball.offsetLeft-5+"px";
    }

    }
    if(e.keyCode==38){
    if(oball.offsetTop<0){
    oball.offsetTop=0
    }else{
    oball.style.top=oball.offsetTop-5+"px";
    }

    }
    if(e.keyCode==39){
    if(oball.offsetLeft>370){
    oball.offsetLeft=370
    }else{
    oball.style.left=oball.offsetLeft+5+"px";
    }

    }
    if(e.keyCode==40){
    if(oball.offsetTop>370){
    oball.offsetTop=370
    }else{
    oball.style.top=oball.offsetTop+5+"px";
    }

    }
    }


    </script>
    </html>

  • 相关阅读:
    ubuntu进入可视化界面
    MYSQL(一)
    PHP(一)
    MAC下安装NLTK
    初次使用NLTK
    iPhone项目的BaseSDK和DeploymentTarget
    ratelimit+redis+lua对接口限流
    java操作RabbitMq
    二维码生成并在下方添加文字,打包下载
    Redis六大淘汰策略:新来的员工不小心把Redis服务器撑爆了!!!
  • 原文地址:https://www.cnblogs.com/huangping199541/p/11432407.html
Copyright © 2011-2022 走看看