温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

这么用原生js操作dom实现上下左右移动

发布时间:2022-03-14 17:17:09 来源:亿速云 阅读:567 作者:iii 栏目:web开发

这篇文章主要介绍“这么用原生js操作dom实现上下左右移动”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“这么用原生js操作dom实现上下左右移动”文章能帮助大家解决问题。

代码如下:

<!DOCTYPE html>

<html lang="en">

<head>

         <meta charset="UTF-8">

         <title>Document</title>

         <style>

         *{

                   padding: 0;

                   margin:0;

         }

 

         html,body,main{

                   height: 100%;

                   width: 100%;

         }

         .box{

                   height: 20px;

                   width: 20px;

                   border-radius: 50%;

                   background:red;

                   position: absolute;

                   left: 0;

                   right: 0;

         }

         .lookFood{

                   font-size: 20px;

                   position: absolute;

                   left: 50%;

                   top:40px;

                   transform: translateX(-50%);

         }

         .food{

                   height: 20px;

                   width: 20px;

                   background: #faa;

                   border-radius: 50%;

                   position: absolute;

         }

 

         footer span{

                   position: absolute;

                   bottom: 20px;

                   left: 50%;

                   transform: translateX(-50%);

         }

         </style>

 

</head>

<body>

<main>

         <div class="lookFood">获取了<span>0</span>food</div>

         <div class="box"></div>

         <div class="food"></div>

</main>  

<footer>

         <span>小提示:按下&uarr;&darr;&larr;&rarr;方向键开始收集食物吧</span>

</footer>

</body>

 

<script>

var box = document.getElementsByClassName("box")[0],

         food = document.getElementsByClassName("food")[0],

         span = document.getElementsByTagName("span")[0],

         //获取的食物个数

         i = 0;

//初始化food的位置;每次吃到调用

function foodInit() {

         food.style.left = Math.random() * parseInt(window.getComputedStyle(document.body).width) - 20 + "px";

         food.style.top = Math.random() * parseInt(window.getComputedStyle(document.body).height) - 20 + "px";

         //获取随机的16进制颜色值;

         food.style.background = '#' + (~~(Math.random() * (1 << 24))).toString(16);

}

//小球每次运动调用这个函数 判断有没有找到食物;

function start() {

         var boxLeft = parseInt(window.getComputedStyle(box).left),

                   boxTop = parseInt(window.getComputedStyle(box).top),

                   foodLeft = parseInt(window.getComputedStyle(food).left),

                   foodTop = parseInt(window.getComputedStyle(food).top);

         //console.log(Math.abs(boxLeft - foodLeft) + "left+" + Math.abs(boxTop - foodTop) + "top+" + parseInt(window.getComputedStyle(food).height))

         if (Math.abs(boxLeft - foodLeft) < parseInt(window.getComputedStyle(food).width) && Math.abs(boxTop - foodTop) < parseInt(window.getComputedStyle(food).height)) {

                   span.innerHTML = ++i;

                   foodInit()

         }

}

 

/**

 *键盘上下左右触发dom移动;

 *可以同时触发两个方向的事件;

 *传入四个参数:dom 需要移动的dom;

 *main 移动的范围容器

 *speed 每秒移动速度;

 *callback 每次执行触发的函数;

 */

var keyDomMove = (function() {

         //通过闭包保存变量

         var keyCode = {

                   //每次按下上下左右的将当前按下的方向保存 ture;

                   downKeyCode: function(e) {

                            var e = e || window.event;

                            //只需要用到上下左右 只保存4个键值;

                            if (e.keyCode === 37 || e.keyCode === 38 || e.keyCode === 39 || e.keyCode === 40) {

                                     keyCode[e.keyCode] = true;

                            }

                   },

                   //每次弹起上下左右的将当前弹起的方向修改为flase;

                   upKeyCode: function(e) {

                            var e = e || window.event;

                            if (keyCode[e.keyCode]) {

                                     keyCode[e.keyCode] = false;

                            }

                   },

                   //用于保存当前的setInterval;通过定时器增强小球移动的连贯性;

                   time: {},

         };

         return function(dom, main, speed,callback) {

                   if (typeof speed != "number") {

                            speed = 1;

                   } else {

                            //速度必须大于60px每秒;每次移动的像素小于1px 浏览器会修正为0px;这也是因为运用了定时器的缺点;

                            //除以60是因为浏览器播放动画每秒60帧可以保持动画的流畅性;

                            speed = (speed/60) > 1 ? (speed/60) : 1

                   }

                   var left = parseInt(window.getComputedStyle(dom).marginLeft),

                            top = parseInt(window.getComputedStyle(dom).marginTop),

                            mainHeigeht=parseInt(window.getComputedStyle(main).height)-20,

                            mainWidth=parseInt(window.getComputedStyle(main).width)-20,

                            //用于左右 和上下穿透;

                            changeXY=function(xy,min,max){

                                     if(xy<min){

                                               xy=max;

                                     }else if(xy>=max){

                                               xy=min;

                                     }

                                     return xy;

                            };

 

                   document.addEventListener("keydown", function(e) {

                        e.preventDefault()

                            keyCode.downKeyCode();

                            if (keyCode[37] && !keyCode.time[37]) {

                                     keyCode.time[e.keyCode] = setInterval(function() {

                                               var x= dom.offsetLeft - left - speed ;

                                               x=changeXY(x,0,mainWidth);

                                               dom.style.left =x+"px";

                                               callback&&callback();

                                     }, 50/3)

 

                            };

                            if (keyCode[38] && !keyCode.time[38]) {

                                     keyCode.time[e.keyCode] = setInterval(function() {

                                               var y = dom.offsetTop - top - speed

                                               y=changeXY(y,0,mainHeigeht);

                                               dom.style.top=y+"px";

                                               callback&&callback();

                                     }, 50/3)

 

                            };

                            if (keyCode[39] && !keyCode.time[39]) {

                                     keyCode.time[e.keyCode] = setInterval(function() {

                                               var x= dom.offsetLeft - left + speed ;

                                               x=changeXY(x,0,mainWidth);

                                               dom.style.left =x+"px";

                                               callback&&callback();

                                     }, 50/3)

 

                            };

                            if (keyCode[40] && !keyCode.time[40]) {

                                     keyCode.time[e.keyCode] = setInterval(function() {

                                               var y = dom.offsetTop - top + speed ;

                                               y=changeXY(y,0,mainHeigeht);

                                               dom.style.top=y+"px";

                                               callback&&callback();

                                     }, 50/3)

 

                            };

                            //每次弹起按键 移除当前方向的定时器 ;

                            document.addEventListener("keyup", function(e) {

                                     keyCode.upKeyCode();

                                     clearInterval(keyCode.time[e.keyCode]);

                                     keyCode.time[e.keyCode] = null;

                            })

                   })

 

         }

 

})()

 

function init() {

         foodInit(food);

         keyDomMove(box, document.body,500,start);

}

init()

</script>

</html>

关于“这么用原生js操作dom实现上下左右移动”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注亿速云行业资讯频道,小编每天都会为大家更新不同的知识点。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI