2011-05-12 68 views
2

在下面的switch语句中,当左键被按下时,它会向左提醒,并且当顶键被按下时,它会提醒顶部。我怎样才能使移位和左键组合的情况。jQuery e.which在switch语句中

$(document).keydown(function(e) { 
    switch (e.which) { 
     case 37: alert('left'); //left arrow key 
      break; 
     case 38: alert('top');; //up arrow key 
      break; 
     case ??: alert('shift + left'); //How can i make this repond to the combination of shift + left arrow keys. 
      break; 
    } 
}); 

回答

5

shift键是一个修饰符,可以在case语句中为左键检查。

$(document).keydown(function(e) { 
    switch (e.which) { 
    case 37: 
     if (e.shiftKey) { 
      alert('shift+left'); // shift and left arrow key 
     } 
     else { 
      alert('left'); //left arrow key 
     } 
     break; 
    case 38: 
     alert('top'); //up arrow key 
     break; 
    } 
}); 

演示:http://jsfiddle.net/ZL9Fx/1/

+0

感谢。它效果很好。在使用条件快捷键“e.shiftKey”之前,我尝试了同样的事情? alert('shift + left'):alert('left');'我也试过'e.which == 16? alert('shift + left'):alert('left');'并且它不起作用。是否有这个快捷方式不起作用的原因。 – Pinkie 2011-05-12 21:45:17

+1

@Pinkie,试试'alert(e.shiftKey?'shift + left':'left')' – 2011-05-12 21:48:36

+0

@Pinkie:这对我很有用:http://jsfiddle.net/ZL9Fx/2/ – 2011-05-13 02:10:57