Home > Article > Web Front-end > Detailed explanation of the steps for jQuery to control divs to move up, down, left, and right through the arrow keys
This time I will bring you jQuery Detailed explanation of the steps to control divs to move up, down, left, and right through the arrow keys. What are the precautions for using jQuery to control divs to move up, down, left, and right through the arrow keys? The following are Let’s take a look at practical cases. In CSS, when the
position<a href="http://www.php.cn/wiki/902.html" target="_blank"> attribute of the DOM element is </a>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. Using the above attributes, we can simply realize the movement effect of an element on the page. Here we use JQuery's
method to achieve the animation effect and use keydown
to monitor The event of pressing the direction key ( uses keydown instead of keyup here so that the element can keep moving while the direction key is pressed. Keydown listens for the press event, and keyup listens for 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
. The core code is as follows:
$(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:
jQuery控制p移动 <script> $(document).keydown(function(event){ var keyNum = event.which; //获取键值 var Item = $(&#39;#switcher&#39;); //要移动的元素 Item.css({position:&#39;relative&#39;}); //设置position switch(keyNum){ //判断按键 case 37: Item.animate({left:&#39;-=20px&#39;});break; case 38: Item.animate({top:&#39;-=20px&#39;});break; case 39: Item.animate({left:&#39;+=20px&#39;});break; case 40: Item.animate({top:&#39;+=20px&#39;});break; default: break; } }); </script>
I believe you have mastered the method after reading the case in this article, more Please pay attention to other related articles on the php Chinese website!
Recommended reading:
Detailed explanation of the steps to implement the electronic clock function with jQueryDetailed explanation of the use of Vue nextTick mechanismThe above is the detailed content of Detailed explanation of the steps for jQuery to control divs to move up, down, left, and right through the arrow keys. For more information, please follow other related articles on the PHP Chinese website!