jQuery keyboard events on DOM elements

放肆的年华 提交于 2019-12-11 05:53:59

问题


I'm building a project where I will have two divs which have their CSS switched up on different individual keypresses.

I am using this jQuery library: https://github.com/jeresig/jquery.hotkeys/

You can see a simple demo here: http://lazarogamio.com/projects/key_test/

Here is my HTML:

<div class="test_box" id="red"></div>

<div class="test_box" id="green"></div>

My CSS:

.test_box {
width: 200px;
height: 200px;
border: 2px solid #000;
margin: 20px;
float: left;
}

.red {
background-color: red;
}

.green {
background-color: green;
}

And my jQuery:

function keymap(){

$(document).bind('keydown', 'r', function (evt){
    $('#red').toggleClass('red');
    });

$(document).bind('keydown', 'g', function (evt){
    $('#green').toggleClass('green');
    });
};

$(document).ready(keymap);

At the moment, the keydown event is working, but for every key, and for both divs. I originally had each div controlled by a separate function, but my results were the same. I also tried to map other keys to do nothing, to no avail. My hunch is that I am not targeting the keys properly, or perhaps not binding the function to the correct object?


回答1:


You're including hotkeys before you include jQuery. It needs to be the other way around. Currently, you're just binding to keydown like normal and the hotkeys include has no effect.

If you include jQuery first, it should work as you expect:

http://jsfiddle.net/ExplosionPIlls/GGvrd/



来源:https://stackoverflow.com/questions/14741537/jquery-keyboard-events-on-dom-elements

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