DOM元素上的jQuery键盘事件 [英] jQuery keyboard events on DOM elements

查看:121
本文介绍了DOM元素上的jQuery键盘事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立一个项目,其中有两个div,它们的CSS分别在不同的按键上切换.

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

我正在使用以下jQuery库: https://github.com/jeresig/jquery.hotkeys/

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

您可以在此处看到一个简单的演示: http://lazarogamio.com/projects/key_test/

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

这是我的HTML:

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

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

我的CSS:

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

.red {
background-color: red;
}

.green {
background-color: green;
}

还有我的jQuery:

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);

此刻,keydown事件正在起作用,但对于每个键以及两个div都有效.最初,每个div由一个单独的函数控制,但是我的结果是相同的.我还尝试映射其他键,但无济于事.我的直觉是我没有正确地定位键,或者可能是没有将功能绑定到正确的对象上?

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?

推荐答案

在包含jQuery之前,您要包含hotkeys .它需要反过来.目前,您只是像普通一样绑定到keydown,而hotkeys包含无效.

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.

如果您首先包含jQuery,它应该可以按预期工作:

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

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

这篇关于DOM元素上的jQuery键盘事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆