我做了一个快速而肮脏的例子,此时它没有样式,但这样的东西可以工作。
JsFiddle 运行示例:http: //jsfiddle.net/29vBZ/3/
您可以相应地用 slideDown() 和 slideUp() 替换 show() 和 hide() 以创建某种眼睛糖果,就像我在这里所做的那样:http: //jsfiddle.net/29vBZ/6/
HTML:
<div id="customSelect">
<div id="customSelectCaption"></div>
<div class="customSelectItem" identifier="in_H2O">in H2O</div>
<div class="customSelectItem" identifier="in_HG">in Hg</div>
<div class="customSelectItem" identifier="psi">psi</div>
<div class="customSelectItem" identifier="cm_H2O">cm H2O</div>
<div class="customSelectItem" identifier="cm_HG">cm Hg</div>
<div class="customSelectItem" identifier="kPa">kPa</div>
</div>
JavaScript/jQuery:
$(document).ready(function(){
//hide the options on load
$('#customSelect').children('.customSelectItem').hide();
//give it the caption of the first option as default.
var firstChild = $('#customSelect .customSelectItem');
$('#customSelect').attr('identifier', firstChild.attr('identifier'));
$('#customSelectCaption').html(firstChild.html());
//set a variable so we know in which state it is.
$('#customSelect').data('customSelectState', false);
//bind the click event so you can take action on click.
$('#customSelect').click(function(event){
if($('#customSelect').data('customSelectState') == false)
{
//hide the caption, show the items.
$('#customSelectCaption').hide();
$('.customSelectItem').show();
//set the variable so we know the state is now 'open'.
$('#customSelect').data('customSelectState', true);
}
else
{
//set the new identifier.
$('#customSelect').attr('identifier', $(event.target).attr('identifier'));
//set the new caption.
var newCaption = $(event.target).html();
$('#customSelectCaption').html(newCaption);
//show the caption, hide the items.
$('#customSelectCaption').show();
$('.customSelectItem').hide();
//set the variable so we know the state is now 'closed'.
$('#customSelect').data('customSelectState', false);
}
});
});
要检索当前值,您可以简单地执行以下操作:
var currentSelection = $('#customSelect').attr('identifier');
Ofcource 这仅适用于一个“假”下拉列表,但可以扩展到一个完整的 jQuery 插件,它对多个做同样的事情。我希望这对您有所帮助。