How to check if an select element is still “open”

2019-06-19 11:10发布

Is there anyway I can detect via jQuery if a select form element is active at the moment?

I created this fiddle to demonstrate the problem:

http://jsfiddle.net/E2PhT/2/

When you hover over the "Search"-Link the search form shows up. When you now click on the select-field to open the options inside and then, without choosing anything, leave the form on the right side (move the mouse past the right edge of the grey block), the select-field stays open while everything eles disappears (as it should).

Now I would like to either make the select element inactive again, so it doesn't stay open or prevent the rest of the form from disappearing as long as the select element is still open.

So either way I have to somehow detect if the select field is still open or active. Is there any way to check this state with jQuery?

Thx for help.

标签: jquery forms
2条回答
Summer. ? 凉城
2楼-- · 2019-06-19 11:21

You can use a global Boolean variable like this:

var isFocused;
$(document).ready(function(){
    $('select').focus(function(){
        isFocused = true;
    }).blur(function(){
        isFocused = false;
    });
});
查看更多
▲ chillily
3楼-- · 2019-06-19 11:23

You can try :focus selector:

if (!$("select").is(":focus")) {
    // ...
}

DEMO: http://jsfiddle.net/E2PhT/3/

查看更多
登录 后发表回答