2014-02-08 28 views
10

你可以看到表單我正在這裏:更改佔位符的顏色在下拉

http://www.escalateinternet.com/free-quote.php

這是下拉預算代碼:

  <td><select id="budget" style="width:420px;"> 
       <option value="">Choose Your Budget</option> 
       <option value="250">$250-$500 Per Month</option> 
       <option value="500">$500-$750 Per Month</option> 
       <option value="750">$750-$1000 Per Month</option> 
       <option value="100">$1000-$1500 Per Month</option> 
       <option value="1500">$1500-$2500 Per Month</option> 
       <option value="2500">$2500-$5000 Per Month</option> 
       <option value="5000">$5000-$7500 Per Month</option> 
       <option value="7500">$7500-$10000 Per Month</option> 
       <option value="10000">$10,000 or More Per Month</option> 
      </select></td> 

哪有我使其成爲「選擇您的預算」與默認情況下其餘佔位符相同的灰色文本,然後在選擇預算時文本是較暗的顏色。我只是想從根本上使其形式的其餘部分使用的配色方案搭配...

回答

-4

可以option:checked

<style> 
    #budget option:checked{ 
     color:red; 
    } 
    </style> 

看看這個演示使用僞類:http://jsbin.com/gilip/1

+0

你在哪裏看到演示中的紅色? – user3286482

+0

單擊下拉菜單並選擇一個值,然後再次單擊它,您將看到上一個選定的項目呈紅色。 – SaidbakR

+0

我不知道爲什麼要投票?該演示工作正常,並將其設置爲正確的答案?! – SaidbakR

8

可能重複的How do I make a placeholder for a 'select' box?

它的缺點是,select元素不支持佔位符,你想做的事情在css中是不可實現的。然而;一些簡單的JS可以幫助我們在這裏。

(我假設你使用jQuery)

$(document).ready(function(){ 
    $('select').on('change', function(){ //attach event handler to select's change event. 
             //use a more specific selector 

     if ($(this).val() === ""){ //checking to see which option has been picked 

      $(this).addClass('unselected'); 
     } else {     // add or remove class accordingly 
      $(this).removeClass('unselected'); 
     } 

    }); 
}); 

獎金編輯:if/else語句塊能夠被重構到一個線(見jquery .toggleClass()):

$(this).toggleClass('unselected', $(this).val() === ""); 

我d還建議給它disabled屬性。然後,您可以添加樣式是這樣的:

select{ 
    color: black; 
} 
select.unselected{ 
    color: gray; 
} 
//edit: you might want to do this to make it that bit nicer: 
select option:first-child{ 
    display: none; 
} 

不要忘記給select元素的初始級的unselected

希望這有助於!

+0

-1,當沒有JS標記時爲Javascript,沒有jQ標記時爲jQuery。 – bjb568

+9

當提問者不知道他需要使用JavaScript時,他應該如何標記JavaScript? – Bill

+0

此外,我沒有可能使用HTML或CSS的解決方案,正如我在答覆開始時所解釋的,所以我使用JavaScript提供了一個可能的解決方案。 @ bjb568 – Bill

1

不使用jQuery的簡單方法。

select { 
      color: #aaa; /* default unselected color */ 
    } 

    select:focus { 
      color: red; /* color when focused */ 
    } 

    #budget option:checked{ 
      color: red; /* color when selected but not focused */ 
    } 
相關問題