2012-06-15 107 views
0

我在页面上有2个div,我希望用户能够用箭头键移动。我尝试通过使用焦点来区分它们,但是太多的项目(如输入)可以获得焦点。目前,当我点击div的时候,我正在使用虚线“聚焦”的css样式,使其脱颖而出,并从其他div中删除样式。用箭头键移动元素

.focused{ 
    border: 1px dashed #cccccc; 
} 


$('#tagCommon').click(function(){ 
    $(this).focus().addClass("focus2"); 
    $('#tagLatin').removeClass("focus2"); 
}); 

我认为this将工作拦截关键事件。

那么,如何才能移动具有focus2类的对象呢?喜欢的东西:

$(document).keydown(function(e) { 
    switch (e.which) { 
    case 37: 
     $('only the div that has class focus2').stop().animate({ 
      left: '-= 10' 
     }); //left arrow key 
     break; 
    } 
}); 

非常感谢您的再次拯救我, 托德

+1

在这个问题的答案,与'.focus2'替换'div'。 – Blender

+0

谢谢......我一直在研究这个问题很久,我没有在我面前看到答案。 DOH! – maddogandnoriko

回答

4

我不知道,如果你仍然需要一个解决方案或没有,但你可以检查这一个: http://jsfiddle.net/ft2PD/41/

下面是HTML

<div id='div1'> 
    <input type='text' value='hello' /> 
</div> 

<div id='div2'> 
    <label> World</label> 
</div> 

这里是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; 
}​