Choose and select div elements with keyboard arrows and enter keys?

血红的双手。 提交于 2019-12-06 13:44:50

问题


Is there any way of navigating through a grid of div elements by pressing the arrow keys on the keyboard, and "clicking" the selected div by pressing enter key? I know that I should at least try to make this work somehow but I'm completely clueless as for how to make this happen, and if it's even possible.

I'm aware of that the following will be invalid if not using the mouse, so what can I do to show some kind of "focus" on a specific div?

.show:hover{
    width:94px;
    height:94px;
    border:3px solid black;
}

.lock{
    pointer-events:none;
}

Any hints of where to start? My game's here: http://jsfiddle.net/94jerdaw/WXEes/

EDIT:

Is it possible to navigate the div field as it is, going "up" from the current position or will i have to make a case for every div as an originating point accompanied by every div it should go to in up/down/left/right events?


回答1:


hope your question is still interesting to you. I had some time and I always want to have my own memory game. So I started building your desired functions, for full code see the Fiddle. Because of the fiddle frame you have to click once on the game.

Edit:Sorry there is some trash code in my script, because I forked one of my own basic setups for plugins, will remove it later.

It is not finished yet, but today I will finish it. I builded it as a plugin, because later on I want to add some options. But the idea of key movement should be clear.

I created a Map-Object (You can also use an array, easier I think) for finding positions.

Too much code to post it all here, so here a snippet:

$(window).keydown(function (e) {
    //Initial set first card as selected
    var actCard, nextCard;

    if ($('.cardset').find('.selected').length < 1) {
        $('#card1').addClass('selected');
    } else {
        switch (e.which) {
        case 37: // left
            $('.cardset').find('.selected').cardMoveHorizont('prev', cardMap);
            break;

        case 38: // up
            $('.cardset').find('.selected').cardMoveHorizont('up', cardMap);
            break;

        case 39: // right
            $('.cardset').find('.selected').cardMoveHorizont('next', cardMap);
            break;

        case 40: // down
            $('.cardset').find('.selected').cardMoveHorizont('down', cardMap);
            break;

        default:
            return; // exit this handler for other keys
        }
        e.preventDefault();
    }
});



回答2:


You need to bind event listeners for arrow keys and enter, it can be done easily from JS/jQ

1min google: Binding arrow keys in JS/jQuery



来源:https://stackoverflow.com/questions/15603617/choose-and-select-div-elements-with-keyboard-arrows-and-enter-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!