Home >Web Front-end >JS Tutorial >How to bind arrow keys to control div movement
This time I will show you how to bind the direction keys to control the movement of divs, and what are the precautions for binding the direction keys to control the movement of divs. The following is a practical case, let's take a look.
In CSS, when theposition<a href="http://www.php.cn/wiki/902.html" target="_blank"></a> attribute of the DOM element is
absolute or relative, we can change this The specific values of the left and top attributes of the element control the position where the element appears on the page.
animate method of JQuery to achieve the animation effect, using
keydownListen to the event of pressing the direction key (
Keydown is used here instead of keyup, so that the element can keep moving when the direction key is pressed. Keydown is to monitor the press event, and keyup is to monitor the key. Release event ). Here we can also take advantage of a feature of the animate method, which is that when the value of its attribute is '=' or '-=', it will first calculate based on the original value and then assign it to the corresponding Attribute, this is consistent with C's
operator.
$(document).keydown(function(event){ var keyNum = event.which; //获取键值 var Item = $('#switcher'); //要移动的元素 Item.css({position:'relative'}); //设置position switch(keyNum){ //判断按键 case 37: Item.animate({left:'-=20px'});break; case 38: Item.animate({top:'-=20px'});break; case 39: Item.animate({left:'+=20px'});break; case 40: Item.animate({top:'+=20px'});break; default: break; } });The complete sample code is as follows:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> jQuery控制p移动</title> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> </head> <body> <p id="switcher" style="width:200px;height:200px;border:solid 1px #000;"> </p> <script> $(document).keydown(function(event){ var keyNum = event.which; //获取键值 var Item = $('#switcher'); //要移动的元素 Item.css({position:'relative'}); //设置position switch(keyNum){ //判断按键 case 37: Item.animate({left:'-=20px'});break; case 38: Item.animate({top:'-=20px'});break; case 39: Item.animate({left:'+=20px'});break; case 40: Item.animate({top:'+=20px'});break; default: break; } }); </script> </body> </html>I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to the php Chinese website Other related articles! Recommended reading:
How does console print log information
The above is the detailed content of How to bind arrow keys to control div movement. For more information, please follow other related articles on the PHP Chinese website!