DDR爱好者之家 Design By 杰米

 本文实例为大家分享了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> 

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

DDR爱好者之家 Design By 杰米
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
DDR爱好者之家 Design By 杰米