jquery:自定义选择框?

问题描述:

嘿家伙, 我试图做一个相当简单的选择框自己。jquery:自定义选择框?

<div class="select"> 
    <ul> 
     <li class="option darr">Dropdown one</li> 
     <li class="option">Dropdown two</li> 
     <li class="option">Dropdown three</li> 
    <ul> 
</div> 

当页面加载时,只有第一个li-item被设置为display:block。当我点击第一个时,应显示所有选项。

到目前为止好...

/*select box*/ 
$('.select ul li.option').click(function() { 
    $('.select ul li.option').fadeIn('fast'); 
}); 

但是现在我卡住了。当我点击例如在第二个选项中,应该有.darr类应用,并且下拉列表应该再次折叠,第二个选项可见。你知道我的意思!

任何想法如何解决?用toggle()?

这是一个小提琴,所以你明白我的意思! http://jsfiddle.net/WFTvq/

$('.select ul li.option').click(function() { 
     $(this).siblings().toggle().removeClass('darr'); 
     $(this).addClass('darr'); 
    }); 

你能检查一下吗?

+0

谢谢你完美。当没有选中任何项时,是否有机会折叠选择框? http://jsfiddle.net/WFTvq/2/如果我在显示所有选项后单击选择框 - 当我不选择其中一个选项并单击屏幕其余部分的任何位置时,选择框不会自动折叠。任何实施这种行为的机会。 – matt 2011-03-05 18:36:16

尝试

$('.select ul li.option').click(function() { 
$('.select ul li.option').fadeIn('fast'); 
$('.select ul li.darr').removeClass('darr'); 
$(this).addClass('darr');}); 
+0

是的,这适用于类,但是如何在点击时隐藏所有其他选项。它应该切换。如果只有一个选项是可见的,我点击所有选项应该显示。当我点击不同的选项时,下拉菜单应该再次崩溃,只有选中的选项应该可见。 – matt 2011-03-05 16:06:00

使用CSS和jQuery:

CSS:

.select { 
    width: 10em; 
    margin: 0 auto; 
} 

li.option { 
    width: 100%; 
    border: 1px solid #ccc; 
    display: none; /* <- hides the li elements of class 'option' */ 
} 

ul:hover li.option { 
    display: block; /* <- shows all options on ul:hover */ 
} 

li.option.darr { 
    display: block; 
} 

的jQuery:

$('li.option').click(
    function(){ 
     $('.darr').removeClass('darr'); 
     $(this).addClass('darr'); 
    }); 

JS Fiddle demo

有一个很好的方法来做到这一点! ^^我做到了几秒钟前)

HTML

<div class="styledSelect"> 
       <span class="styledSelectValue"></span> 
       <select name="type"> 
        <option value="">Par type de propriété</option> 
        <option value="choix2">choix2</option> 
        <option value="choix3">choix3</option> 
       </select> 
      </div> 

CSS

.styledSelect{/*your css for the background image... it will be the body of your select*/} 
.styledSelect select{/*your css with opacity:0;*/} 
.styledSelectValue{/*the css of the received value*/} 

jQuery的

$('.styledSelect').each(function(){ 
      selectValue = $(this).children("select").val(); 
      if(selectValue == ""){selectValue = $(this).children("select").children("option:eq(0)").text();} 
      $(this).children(".styledSelectValue").text(selectValue); 
     }); 
     $('.styledSelect select').change(function(){ 
      selectValue = $(this).val(); 
      if(selectValue == ""){selectValue = $(this).children("option:eq(0)").text();} 
      $(this).parent(".styledSelect").children(".styledSelectValue").text(selectValue); 
     }); 

这是我找到的最好的方式;)