使用箭头键移动元素 [英] Move elements with arrow keys
问题描述
我在页面上有2个div,希望用户能够使用箭头键来回移动.我尝试通过使用焦点来区分它们,但是太多的项目(例如输入)无法获得焦点.当前,当我单击div时,我正在应用带有虚线的集中式" css样式以使其突出并从另一个div中删除该样式.
I have 2 div's on a page that I want the user to be able to move around with the arrow keys. I tried differentiating them by using focus but too many items(like inputs) can get focus. Currently when I click the div's I am applying a "focused" css style with a dotted line to make it stand out and removing the style from the other div.
.focused{
border: 1px dashed #cccccc;
}
$('#tagCommon').click(function(){
$(this).focus().addClass("focus2");
$('#tagLatin').removeClass("focus2");
});
我认为这将用于拦截按键事件.
I think this will work to intercept the key up events.
那么我该如何只移动具有focus2类的对象呢?像这样:
So how can I move just the object that has the class of focus2? Something like:
$(document).keydown(function(e) {
switch (e.which) {
case 37:
$('only the div that has class focus2').stop().animate({
left: '-= 10'
}); //left arrow key
break;
}
});
非常感谢您再次向我伸出援手, 托德
Thank you very much for bailing me out yet again, Todd
推荐答案
我不确定您是否仍然需要解决方案,但是您可以检查一下: http://jsfiddle.net/ft2PD/41/
i'm not sure if you still need a solution or not but you can check this one out: http://jsfiddle.net/ft2PD/41/
这是html
<div id='div1'>
<input type='text' value='hello' />
</div>
<div id='div2'>
<label> World</label>
</div>
这是JavaScript:
and here is the javascript:
$(document).ready(function(){
$('#div1,#div2').click(function(){
$('div.selected').removeClass('selected');
$(this).addClass('selected');
})}).keyup(function(e){
var div = $('div.selected');
console.log(div);
console.log(e.which);
switch (e.which) {
case 37:
$(div).stop().animate({
left: '-=10'
}); //left arrow key
break;
case 38:
$(div).stop().animate({
top: '-=10'
}); //up arrow key
break;
case 39:
$(div).stop().animate({
left: '+=10'
}); //right arrow key
break;
case 40:
$(div).stop().animate({
top: '+=10'
}); //bottom arrow key
break;
}
});
最后放置CSS
#div1
{
position: absolute;
width:100px;
height:100px;
margin:15px;
padding:15px;
border: thin solid #D2D2D2;
}
#div2
{
position: absolute;
width:50%;
margin:15px;
padding:15px;
border: thin solid #D2D2D2;
}
.selected
{
border: 1px dashed #cccccc !important;
}
这篇关于使用箭头键移动元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!