• 运动的小球


      1 <!DOCTYPE html>
      2 <html>
      3 <head>
      4 <meta charset="utf-8">
      5 <title></title>
      6 <style type="text/css">
      7 #box{ 500px;height: 500px;border: 1px solid black;position: relative;}
      8 #ball{ 20px;height: 20px;background-color: red;border-radius: 50%;position: absolute;left: 0;top: 0;}
      9 </style>
     10 </head>
     11 <body>
     12 <div id="box">
     13 <div id="ball">
     14 
     15 </div>
     16 </div>
     17 <input type="button" name="btn" id="btn" value="启动" />
     18 </body>
     19 <script type="text/javascript">
     20 //获取节点
     21 var obox = document.querySelector("#box");
     22 var oball = document.querySelector("#ball");
     23 var obtn = document.querySelector("#btn");
     24 var speed = 10 ;
     25 var topspeed = 0 ;
     26 var t ;
     27 obtn.onclick = function(){
     28 clearInterval(t);
     29 t = setInterval(function(){
     30 
     31 if(oball.offsetLeft>480 ){
     32 speed=-speed;
     33 oball.style.left = oball.offsetLeft + speed + "px";
     34 }
     35 else if (oball.offsetLeft<0 ){
     36 speed=-speed;
     37 oball.style.left = oball.offsetLeft + speed + "px";
     38 }else{
     39 oball.style.left = oball.offsetLeft + speed + "px";
     40 }
     41 
     42 
     43 if(oball.offsetTop>480 ){
     44 topspeed=-topspeed;
     45 oball.style.top = oball.offsetTop + topspeed + "px";
     46 }
     47 else if (oball.offsetTop<0 ){
     48 topspeed=-topspeed;
     49 oball.style.top = oball.offsetTop + topspeed + "px";
     50 }else{
     51 oball.style.top = oball.offsetTop + topspeed + "px";
     52 }
     53 
     54 
     55 document.onkeydown = function(eve){
     56 e=eve||window.event;
     57 //左走
     58 if(e.keyCode==37){
     59 if(speed>0){
     60 
     61 speed=-10;
     62
     63 }else if(speed==0){
     64 speed=-10;
     65 topspeed=0;
     66 }
     67 }
     68 //右走
     69 if(e.keyCode==39){
     70 if(speed<0){
     71 speed=-speed;
     72 
     73 }else if(speed==0){
     74 speed=10;
     75 topspeed=0;
     76 }
     77 }
     78 
     79 //    上走
     80 if(e.keyCode==38){
     81 if(topspeed>0){
     82 topspeed=-10;
     83 
     84 }else if(topspeed==0){
     85 topspeed=-10;
     86 speed=0;
     87 
     88 }
     89 }
     90 
     91 //    下走
     92 if(e.keyCode==40){
     93 if(topspeed<0){
     94 topspeed=10;
     95 
     96 }else if(topspeed==0){
     97 topspeed=10;
     98 speed=0;
     99 
    100 }
    101 }
    102 
    103 }
    104 
    105 },30)
    106 
    107 }
    108 </script>
    109 </html>

      

  • 相关阅读:
    解决ios下iframe不能滑动
    每天一题之js执行顺序
    async函数的返回值
    小程序自定义Tabbar
    windows10配置vue3项目踩坑记录
    vue2+循环链表解决一个历史趣题
    小程序内协议使用的三种方法
    HDFS的java操作
    HDFS工作原理笔记
    win10已经编译好的hadoop2.6.5
  • 原文地址:https://www.cnblogs.com/huangping199541/p/11444114.html
Copyright © 2020-2023  润新知