Javascript implements the principle and code for moving or changing div through keyboard operations

Source: Internet
Author: User

Yesterday, we recorded the event of getting the value of the keyboard key. With the value, we only need to perform different operations on different values. We also used it before when writing a snake. As a result, it was a long time, so I felt it was necessary to record the merits. On the one hand, I also reminded myself that the newly implemented functions turned into strangers, in general, it's just a warm story.

In this case, let's analyze the principle of moving the div through the keyboard:

* --- To move a div, you must first obtain the div object.

* --- Postion: absolute: drag the div completely out of the Document Stream. This part is missing. I went back to view the snake and found it. It was dizzy.

* --- Obtain the keyboard operation

* --- Provide different responses based on different keyboard operations


This is what I think of. Let's look at the code first:

First, the html section

<div style="width: 50px;height: 50px;background-color: cyan;position: absolute;" id="showZone">


Then, record the actual javascript operations.

Window. onload = function () {var obj = document. getElementById ("showZone"); // get the object, which is the simplest var a = 10; var toLeft = toRight = toTop = toBottom = false; // define several boolean variables for subsequent operations. See var move = setInterval (function () in four directions () {// The move definition in this place is actually meaningless, just to make this method more explicit if (toLeft) {obj. style. left = parseInt (obj. offsetLeft-a) + "px"; // it is best to write parseInt. In addition, because offsetLeft does not contain px, do not forget "px"} if (toRight) {obj. style. left = obj. offsetLeft + a + "px "; // It can be done without writing parseInt. Is it because of the execution sequence of javascript? Execute +, then execute +, and then execute =? The implementation result is} if (toTop) {obj. style. top = obj. offsetTop-a + "px";} if (toBottom) {obj. style. top = obj. offsetTop + a + "px" ;}}, 300); // This classic timer, a large artifact of loop execution. Do you still remember the difference between setInterval and settimeout? document. onkeydown = function (event) {var event = event | window. event; switch (event. keyCode) {// Haha, get the keyboard operation. case 37: toLeft = true; break; // change the variable and continue executing the initial loop, if you do not stop, you cannot stop. 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; // change it back so that you can stop it. 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 up, down, left, and right buttons to move up, down, and right divs. Next, record sensitive areas.

1. div needs to be absolute. It is not worthwhile to tangle with it for a long time. So I checked it and learned about the concept "Document Stream ",

Document Stream, usually the elements are arranged from top to bottom and from left to right. This element is a node element and a huge dom. Let's talk about other explanations first. What I like most is to elaborate on this: Document + stream. As the name suggests, the document is a webpage document, while the stream is an output method, another explanation is the browser's parsing method. This seems to be a little more vivid. A normal Document Stream is like a plane, and where you put an element, it is, the floating, fixed positioning, and relative positioning are analyzed here. absolute is used to re-generate a stream, instead of its parent layer label, as if the previous z-index is 0, the z-index is above it, and it is suspended out of thin air. You can move it through left and top.

I can understand it in general, but I still cannot express it in words in some places, and some points are slightly vague. I believe that with the accumulation of experience, I can understand it more deeply.

2. the keyCode here is capitalized, The onkeyup and the onkeydown are in lower case. This is also a problem found only after testing. For javascript, it is a big problem in every small place;

3. The break in the switch. This is often encountered in java.

The general problem is the above points, but do you still remember the commented shortcut keys and other shortcut keys? This is a problem. The above response is only for a single button, if we want to use some shortcut keys, how can we set them?

Let's take a look at the Code:

Document. onkeydown = function (event) {// It's similar to the code above. Do you see the difference? 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; // here, case 39: toRight = true; break; case 40: toBottom = true; break ;}};


Another attribute of the event object is encountered here. It is another attribute other than the keyCode, ctrlKey, or capital. Its main function is to check the status of the ctrl key. In fact, there are two such attributes:

AltKey and shiftKey check the status of the alt and shift buttons respectively, so that you know how to set a shortcut key.

In fact, if it was written by myself, it may be satisfying to me, but when I look through the search, I can always meet a thoughtful friend.

The code is attached. Do you know what to do:

Function limit () {var doc = document.doc umentElement. clientWidth, document.doc umentElement. clientHeight] // prevents overflow on the left. 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> // prevents top overflow obj. offsetTop <= 0 & (obj. style. top = 0); // prevent overflow on the right. doc [0]-obj. offsetLeft-obj. offsetWidth <= 0 & (obj. style. left = doc [0]-obj. offsetWidth + "px"); // prevents bottom overflow doc [1]-obj. offsetTop-obj. offsetHeight <= 0 & (obj. style. top = doc [1]-obj. offsetHeight + "px ")}

I have attached the online code to prevent overflow. I also want to likes this writing method, which is much shorter than what I wrote, try to write a short point later.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.