Is there a way to determine if a <select> dropdown menu is open?

Deadly 提交于 2019-11-27 09:11:58

You can play with mouseenter event in select's option child elements as you can only enter in them if select menu is open, or also with the click event on the select element, usually thrown when you open it.

To test in a precise moment if its open or not I think is not possible.

Select elements are notoriously tricky in Internet Explorer. I don't think there is any way of reliably determining if one is open or closed.

I can see if the select is open, and then when it closes if the user selects a new option, or completely blurs the select. However, if you click on the same option, or just click out of the select once (closing it but not blurring it), it still shows "down". Working on a more complete solution. So, expect this answer to have edits...

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script type="text/javascript">
  var selected
$( document ).ready(


 function()
 { 
  $( '#test' )
      .mousedown( function(){ console.log( 'down' ); selected = $( this ).val() } )
      .blur( function(){ console.log( 'out' ) } )
      .change( function(){ console.log( 'out' ) } )
      .mouseleave( function(){ console.log( 'out' ) } )
      .mouseup( function(){ 
         if( $( this ).val() == selected ) 
           console.log( 'out' )
    }
   )
 } // function

) // ready
</script>

<select id="test">
 <option>1</option>
 <option>2</option>
</select>

Edit: added mouseout

Edit2: added mouseup - works now!

A more complete solution would be:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.pack.js"></script>
<script type="text/javascript">
var selected,selected2
$( document ).ready(


 function()
 { 
  $( 'select[id$="test"]' )
      .mousedown( function(){ 
        console.log( 'predown' );
        if( $( this ).val() != selected ) {
          console.log( 'down' ); 
          selected = $( this ).val();
          selected2=null;} 
        else  
          selected=null;} )
      .blur( function(){ if (selected2==selected) {
        console.log( 'outb' );
        selected=null;
        selected2=null;} } )
      .mouseup( function(){ console.log( 'preoutu' );
         if( $( this ).val() != selected || $( this ).val() == selected2 ) {
            console.log( 'outu' );
            selected=null;
            selected2=null;
         }
         else
           selected2=$( this ).val();   
    }
   )
 } // function

) // ready
</script>


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