简体   繁体   English

我如何测试输入是否集中在if结构中?

[英]How can I test whether input has focus in an if structure?

I've got this code here now, but the alerts still come up after you click on the input, when it doesn't have focus. 我现在已经在这里获得了此代码,但是当您单击输入时,如果没有焦点,警报仍然会出现。 I would like to get rid of the click function too, if possible, so that it only alerts when the input has focus. 如果可能的话,我也想摆脱单击功能,以便它仅在输入具有焦点时发出警报。

$('#inputSize').click(function(){
    if ($('#inputSize').is(':focus')){
        $(document).keydown(function(e){
            if (e.keyCode == 38) { 
               alert( "up pressed" );
               return false;
            }
                if (e.keyCode == 40) { 
               alert( "down pressed" );
               return false;
            }
        });
    }
});

Thanks! 谢谢!

Just bind to the keydown event on the input. 只需绑定到输入上的keydown事件即可。 There's no need to check for focus, since it's implied: 由于隐含了以下内容,因此无需检查焦点:

$('#inputSize').keydown(function(e) {    
    if (e.keyCode == 38) 
    { 
       alert( "up pressed" );
       return false;
    }

    if (e.keyCode == 40) 
    { 
       alert( "down pressed" );
       return false;
    }
});

There is a handler specifically for focus: 有一个专门针对焦点的处理程序:

$('#inputSize').focus(function () {});

This will call the function passed when the input with the given ID has focus. 当具有给定ID的输入具有焦点时,这将调用传递的函数。

You can test if it's a focused element using document.activeElement as below: 您可以使用document.activeElement如下测试它是否为焦点元素:

  if($('#inputSize') == document.activeElement) {
      // #inputsize is focused
    }

Note though that most of the time your actions are triggered on another element, so if say you clicked a button then it would have focus and now be the active element, so you couldn't check this with a button check, because the element's already changed by the time your event fired, in most cases. 请注意,尽管大多数情况下您的操作是在另一个元素上触发的,所以如果说您单击了按钮,那么它将具有焦点,现在是活动元素,因此您无法通过按钮检查来对此进行检查,因为该元素已经在大多数情况下,事件触发时已更改。

So , you might end up as 因此,您可能最终会

$('#inputSize').click(function(){

      if($('#inputSize') == document.activeElement){
        $(document).keydown(function(e){
            if (e.keyCode == 38) { 
               alert( "up pressed" );
               return false;
            }
                if (e.keyCode == 40) { 
               alert( "down pressed" );
               return false;
            }
        });
    }
});
$('#inputSize').keydown(function(e) {
    if (e.keyCode == 38) 
    { 
       alert( "up pressed" );
       return false;
    }
    if (e.keyCode == 40) 
    { 
       alert( "down pressed" );
       return false;
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM