Show select dropdown in jQuery? [duplicate]

2019-01-12 08:00发布

问题:

Possible Duplicate:
How can you programmatically tell an HTML SELECT to drop down (for example, due to mouseover)?

Is it possible to make the dropdown on a select element visible with jQuery?

I tried using $('#dropdown').click();, but it has no effect.

回答1:

This is not possible. You can only implement your own select-box, but this is bad for usability.

another approach is to programmatically change the size-attribute of the select-box, but this is not really what you wanted.

I suggest to think of why you need this and if there would be a nicer software-pattern?



回答2:

Here's my adaption:

HTML

<button id='btn'>Click Me</button>
<select id='test'>
    <option>Blah 1</option>
    <option>Blah 2</option>
    <option>Blah 3</option>
    <option>Blah 4</option>
</select>

JavaScript

$('#btn').click(function(){
    $('#test').attr('size', 5);
});

$('#test').change(function() {
   $(this).attr('size', 1); 
});

This doesn't open the drop list, but it kind of works.

Demo here.



回答3:

No - you are unable to do this. It's roughly along the same lines of a button in it's pressed state when a user clicks it - an 'interim' operation for the user to set a value. You could focus to it, but that's about it.

If you really wanted to simulate this, you could play with some CSS. For example, you could create a list that looks like the dropdown list and set the dropdown value based on whatever the user clicks - similar to how an autocomplete list looks.

You could always change it to a multiple line list box if you wanted to display all the values to the user. You'd do this by setting the size to any value and back to 1 when you want to hide. It's not perfect, but it's another option:

$("#open").click(function(e){
   e.preventDefault();
   $("#myselect").attr("size",5);    
});

$("#myselect").click(function(){
   $(this).attr("size",1); 
});

http://jsfiddle.net/jonathon/cr25U/