2011-03-05 159 views
1

嘿傢伙, 我試圖做一個相當簡單的選擇框自己。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/

回答

2
$('.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

0

嘗試

$('.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

0

使用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

1

有一個很好的方法來做到這一點! ^^我做到了幾秒鐘前)

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); 
     }); 

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