• 运动的小球自动变键盘控制


    <!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>

  • 相关阅读:
    以此来励志吧!!!(选自:知乎)
    【P1303】苹果二叉树
    【P1813】8的倍数
    2016.9.4 の 測試
    后缀数组
    个中模板
    基数排序
    【NOIP2014D2T3】解方程
    【HAOI2006】【BZOJ1051】【p1233】最受欢迎的牛
    java安全性-引用-分层-解耦
  • 原文地址:https://www.cnblogs.com/huangping199541/p/11432407.html
Copyright © 2020-2023  润新知