本站精选了一篇相关的编程文章,网友咸倩语根据主题投稿了本篇教程内容,涉及到js、移动、js实现方块上下左右移动效果相关内容,已被408网友关注,如果对知识点想更进一步了解可以在下方电子资料中获取。
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>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持码农之家。