Home >Web Front-end >JS Tutorial >The principle and code of moving or changing divs through keyboard operation using js_javascript skills
Yesterday, we recorded the event of getting the value of the keyboard key. With the value, it is nothing more than doing different operations for different values, and it has been used before when writing Snake. As a result, it took a long time, so I feel the need to record it. On the one hand, it does have merits, and on the other hand, it reminds myself that the function I just implemented becomes a stranger again. In general, it can be regarded as reviewing the old and learning the new.
Let’s first analyze the general principle of moving divs through keyboard operations:
*---To realize the movement of div, the first and most critical point is to obtain the div object
*---postion: Absolute completely drags the div out of the document flow. I missed this place. I only discovered it when I went back and watched Snake. I’m so dizzy
*---Get keyboard operations
*---give different responses according to different keyboard operations
This is what I think needs to be paid attention to. Let’s look at the code first:
First the html part
<div style="width: 50px;height: 50px;background-color: cyan;position: absolute;" id="showZone">
Then record the actual operation of javascript
window.onload=function(){ var obj=document.getElementById("showZone");//获取到对象了吧,这最简单 var a=10; var toLeft=toRight=toTop=toBottom=false;//定义几个boolean型变量,是为了后面方向操作用的,看是四个方向吧 var move=setInterval(function(){//这个地方的move定义实际上毫无意义,只是为了让这个方法更明显一点 if(toLeft){ obj.style.left=parseInt(obj.offsetLeft-a)+"px";//感觉最好还是写上parseInt,另外,因为offsetLeft是不含px的,所以不要忘记“px” } if(toRight){ obj.style.left=obj.offsetLeft+a+"px";//不写parseInt也可以,难道是因为javascript的执行顺序?执行+,再执行+,再执行=?实现结果来看是 } if(toTop){ obj.style.top=obj.offsetTop-a+"px"; } if(toBottom){ obj.style.top=obj.offsetTop+a+"px"; } },300); //这个经典的定时器啊,循环执行的大神器,还记得setInterval和settimeout的区别么 document.onkeydown=function(event){ var event=event||window.event; switch(event.keyCode){ //哈哈,获取到键盘操作了吧 case 37:toLeft=true;break;//改变变量,继续执行最初的循环,不让你停不能停啊 case 38:toTop=true;break; case 39:toRight=true;break; case 40:toBottom=true;break; } }; document.onkeyup=function(event){ switch(event.keyCode){ case 37:toLeft=false;break;//给我变回来,让你停就别动了 case 38:toTop=false;break; case 39:toRight=false;break; case 40:toBottom=false;break; } }; };
In this way, we have completed the requirements in the principle analysis. At the same time, we can move the div up, down, left, and right through the up, down, left, and right buttons. Next, let’s record the sensitive places.
1. The div needs to be absolute. It was not worth worrying about this for a long time, so I did some research and learned about the concept of "document flow",
Document flow is usually said to be that elements are arranged from top to bottom and from left to right, then this element is a node element, a huge dom. Let’s talk about other explanations first. I prefer to explain it like this: document flow. Document, as the name suggests, refers to web documents, and flow is the output method. Some explanations say it is the browser’s parsing method. This seems to be more To put it more vividly, the normal document flow is like a plane, and an element will be wherever you place it. As for floating, fixed positioning and relative positioning, analyzing absolute here means regenerating a flow. After being separated from its parent label, it is as if the z-index was 0 before, and this z-index is on top of it. If it is suspended above it, you can move it arbitrarily through left and top.
I can probably understand the meaning, but I still feel that there are some parts that cannot be effectively expressed in words, and some points are slightly vague. I believe that with the accumulation of experience, I can understand it more deeply.
2. The uppercase letters in keyCode and the lowercase letters in onkeyup and onkeydown are problems discovered only after testing. For JavaScript, every small place is a big problem;
3. Break in switch; this is often encountered in java, so I won’t go into details
The general problem is the above points, and do you still remember the shortcut keys for comments? Do you remember other shortcut keys? This raises a question. The response above is only for a single key. If we want to use What about some shortcut keys? How to set them?
Let’s take a look at the code first:
document.onkeydown=function(event){//还是跟上面差不多的代码吧,你看出不同在哪里了么 var event=event||window.event; var bctrl=event.ctrlKey;//在这里 switch(event.keyCode){ case 37:toLeft=true;break; case 38:if(bctrl){obj.style.background="yellow";break;}toTop=true;break;//在这里, case 39:toRight=true;break; case 40:toBottom=true;break; } };
Here we encounter another attribute of the event object, which is another attribute besides keyCode, ctrlKey, still in uppercase letters. Its main function is to check the status of the ctrl key. In fact, there are two such attributes:
altKey and shiftKey are to check the status of the alt key and shift key respectively, so you know how to set a shortcut key.
Actually, if I had written it myself, I might have been very satisfied, but when I was browsing and searching, I could always meet thoughtful friends
Attached is the code, do you know what to do:
function limit(){ var doc = [document.documentElement.clientWidth, document.documentElement.clientHeight] //防止左侧溢出 obj.offsetLeft <=0 && (<span style="font-family: Arial, Helvetica, sans-serif;">obj</span><span style="font-family: Arial, Helvetica, sans-serif;">.style.left = 0);</span> //防止顶部溢出 obj.offsetTop <=0 && (obj.style.top = 0); //防止右侧溢出 doc[0] - obj.offsetLeft - obj.offsetWidth <= 0 && (obj.style.left = doc[0] - obj.offsetWidth + "px"); //防止底部溢出 doc[1] - obj.offsetTop - obj.offsetHeight <= 0 && (obj.style.top = doc[1] - obj.offsetHeight + "px") }
What I am attaching here is the code on the Internet. While preventing overflow, I also want to praise this writing method. It is much shorter than the decisive one I wrote. I will try to write shorter in the future.