微信小程序开发东西_js完成方块上下左右移动效果

js实现方块上下左右移动效果       这篇文章主要为大家详细介绍了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 

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

相关阅读