Home  >  Article  >  Web Front-end  >  jQuery realizes using the arrow keys to control the up, down, left and right movement of the layer_jquery

jQuery realizes using the arrow keys to control the up, down, left and right movement of the layer_jquery

WBOY
WBOYOriginal
2016-05-16 17:43:521039browse

Question: When pressing the direction key, the layer will move smoothly by 20 pixels in the corresponding direction; the key codes of the four direction keys are 37 (left), 38 (top), 39 (right) and 40 (bottom).

Then I wrote the following code :

$div is the layer to be moved, and its position has been set to relative in CSS. At first glance, there seems to be no problem. After running it, I found the following problem:

1. After pressing down, there is no response when pressing up again.

2. After pressing right, there is no response when pressing left.

Later, after a netizen asked me, I suddenly realized:

When you press down, the top value is 20px. At this time, press up. You can see from Firebug that the bottom value at this time is also 20px, and the layer does not move up because the browser first parses top, that is to say {top:20px;bottom:100px} and {top:20px} are the same, no matter what the bottom value is. This is also the reason why there is no response when pressing left after pressing right. The key is the left value.

So I changed the code :

After running, it is as expected, no problem up, down, left, or right.

Experience: I have always known that when positioning, top and left attributes are enough, but I also wrote right/bottom. It is really the details that kill people.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn