How can I add the "button down" effect when a button is selected and a key is pressed? The behaviour of the actual press works, it's just no effect is ever shown.
To be more specific: I have a set of buttons that can be traversed through using the left and right arrow keys. And when Enter is pressed, the currently selected 开发者_开发百科button will carry-out it's onclick behaviour.
Thanks!
Here is a fiddle example: http://jsfiddle.net/maniator/DBLem/
var index = 0;
var buttons = $('button');
var max = buttons.length - 1;
var buttonOn = buttons.eq(index).addClass('on');
$(document).keydown(function(e) {
switch (e.keyCode) {
case 39:
{
index++;
if (index > max) {
index = 0;
}
break;
}
case 37:
{
index--;
if (index < 0) {
index = max;
}
break;
}
case 13:
{
buttonOn.trigger('click');
}
}
buttonOn = buttons.eq(index);
buttons.removeClass('on');
buttonOn.addClass('on');
});
$('button').click(function(){
alert(this.innerHTML);
});
Well i'd save an id of the element which currently has focus like this and then click it when the user presses enter:
var id;
$("button").focus(function () {
id = this.id;
});
$(window).keydown(function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if (code === 13){
$('#'+id).click();
}
});
Try this
$("button").click(function(){
$(this).animate({ marginLeft: "2px", marginTop: "2px" }, 100, function(){
$(this).css({marginLeft:"0px", marginTop:"0px"});
//On click logic goes here
});
}).keyup(function(e){
if(e.which == 13){
$(this).trigger('click');
}
});
精彩评论