jQuery Draggable()和键盘控制 [英] jQuery Draggable() and keyboard control
问题描述
在这里,我有一个在 #person
上启用jQuery Draggable()的页面, #person
受限于 #map
。
Hey there, I have a page with the jQuery Draggable() enabled on #person
and that #person
is constrained to #map
.
(链接到插件: http://docs.jquery.com/UI/Draggables/draggable )
但是,我还用键盘上的箭头键添加了控制。现在,他们都一起玩,直到我到达受限区域的边缘( #map
的边缘)。
However, I have also added control with the Arrow keys on the keyboard. Now, they all play well together until I get to the edge of the constrained area (the edge of #map
).
如果我拖动,则 #person
受限于 #map
- 如果我使用箭头键, #person
可以超越 #map
If I am dragging, then the #person
gets constrained to the #map
- if I use the arrow keys, the #person
can go beyond the edge of #map
.
我如何限制箭头键和draggable?
How can I constrain the arrow keys as well as the draggable?
我的键盘代码控制:
$(document).bind('keydown',function(e){ //set the keydown function as...
switch(e.which) {
case 37: $(characterName).animate({
left: '-=40'
}, 250, function() {
});
break;
}
});
**** phew **** cheers。
****phew**** cheers.
请任何人? [/ EDIT]
Please anyone? [/EDIT]
推荐答案
不幸的是,jQuery UI Draggable没有公开任何方法手动更改元素的位置。当使用键盘移动时,您将需要手动跟踪#个人的位置,并且当它将要超过#map的界限时停止移动它。
Unfortunately, jQuery UI Draggable doesn't expose any methods to manually change the element's position. You will have to track the #person's position manually when moving it with the keyboard, and stop moving it when it is about to exceed the bounds of the #map.
您可以使用jQuery方法,例如 .offset( )和 .position()方法来查找元素的可靠位置。
You can use jQuery methods such as .offset() and .position() methods to find reliable positions for elements.
例如:
$(document).bind(
'keydown',
function(event) {
switch(event.which) {
case 37: {
var character = $(characterName);
var map = $('#map');
if((character.offset().left - 40) > map.offset().left) {
character.animate(
{
left: '-=40'
},
250,
function(){}
);
}
break;
}
}
}
);
这篇关于jQuery Draggable()和键盘控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!