欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

js实现方块上下左右移动效果

程序员文章站 2024-01-17 16:51:40
 本文实例为大家分享了js实现方块移动的具体代码,供大家参考,具体内容如下 ...

 本文实例为大家分享了js实现方块移动的具体代码,供大家参考,具体内容如下

<!doctype html> 
<html> 
  <head> 
    <meta charset="utf-8"> 
    <title></title> 
    <style type="text/css"> 
      #box{ 
        width: 50px; 
        height: 50px; 
        position: absolute; 
        background: palevioletred; 
      } 
    </style> 
  </head> 
  <body> 
    <div id="box" style = "left: 0; top: 50px;"></div> 
    <button id = "btn">stop</button> 
  </body> 
  <script type="text/javascript"> 
    var speed = 10; 
    var flag = true; 
    var interid; 
     
    function moveleft(){ 
      var oldleft = parseint(box.style.left); 
 
      if(oldleft >= window.innerwidth-50 || oldleft < 0){ 
        speed *= -1; 
      } 
      box.style.left = oldleft + speed + "px";   
    } 
     
    function movetop(){ 
      var oldtop = parseint(box.style.top); 
 
      if(oldtop >= window.innerheight-50 || oldtop < 0){ 
        speed *= -1; 
      } 
      box.style.top = oldtop + speed + "px";  
    } 
     
    function onoff(rand){ 
//     var rand = random(); 
      if (flag) { 
        btn.innerhtml = "start"; 
        clearinterval(interid); 
        flag = false; 
      } else{ 
        btn.innerhtml = "stop"; 
        if (rand == 1) { 
          interid = setinterval("moveleft()",50); 
//         flag = true; 
        } else{ 
          interid = setinterval("movetop()",50); 
//         flag = true; 
        }         
        flag = true; 
      } 
    } 
     
    btn.onclick =onoff; 
     
    //产生一个1-2的随机数 
    function random(){ 
      rand = parseint(math.random() * 2 + 1); 
      alert(rand); 
 
      if (rand == 1) { 
        interid = setinterval("moveleft()",50); 
      } else{ 
        interid = setinterval("movetop()",50); 
      } 
    } 
     
    random(); 
     
  </script> 
</html> 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。