当关注某些HTML元素时,如何禁用jQuery按键检测?

时间:2015-10-21 02:44:36

标签: jquery html

目前我的网页启用了一个按键检测功能,当按下A和D时,它会改变图像(图像源)。我刚刚添加了登录,注册功能,但是当我输入用户名或密码时,我有时会点击A和D,图片会发生变化,这是我不想要的,如何在登录元素集中时禁用图片更改功能?

我在想,既然文档选择器选择了整个页面,有没有办法排除某些元素?还是有另一种方法来实现我想要的目标吗?

<div id="loginContainer">
 Username:<br/> <input type="text" name="username"/><br/>
 Password:<br/> <input type="password" name="password"/><br/>
 <input type="button" name="login" value="Login"/>
</div>

----------

$(document).keypress(function(e){
        // key press detection code here
});

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

document.activeElement返回重点项目。你可以检查它是否是某个元素。在每个jQuery函数中,如果return false;它的行为类似于禁用函数

$(document).keypress(function(e){
         if(document.activeElement && document.activeElement != document.body)
             return false;
         // key press detection code here
});

答案 1 :(得分:0)

您可以检查元素是否已聚焦并返回:

$(document).keypress(function(e){
    if( $("input[name='login']").is( ":focus" )) return; 
    // key press detection code here
});

答案 2 :(得分:0)

$(document).keypress(function(e){
     e.stopImmediatePropagation();
     return false;
});