有没有办法改变第一个选项的颜色"选择"为红色,其余选项为绿色?
到目前为止,toggleClass允许我在颜色之间进行更改,但是每当用户点击"选择"时,我希望颜色变为红色,并且每当有人点击其余选项时(即& #34; Service-One,Service-Two"等)。
HTML:
<div class="field">
<label>Service</label>
<select id="select">
<option>Select</option>
<optgroup label="Type of Service">
<option>Service-One</option>
<option>Service-Two</option>
</optgroup>
<optgroup label="Type of Service">
<option>Service-Three</option>
<option>Service-Four</option>
</optgroup>
</select>
</div>
这是我的jQuery:
$("select").each(function(){
$(this).toggleClass('success-select');
});
答案 0 :(得分:1)
只需检查更改时的选择值。 你甚至可以添加一个失败类:
//first color all the options:
$('#select option').css({
"color":"green"
});
//color group names gray:
$('#select optgroup').css({
"color":"#555555"
});
//color first option red:
$('#select option').eq(0).css({
"color":"red"
});
//attach a handler to fire when select value is changed
$('#select').change(function(){
if($(this).val()==="Select"){
$(this).removeClass("success-select");
$(this).addClass("failure-select");
}
else{
$(this).removeClass("failure-select");
$(this).addClass("success-select");
}
});
&#13;
form {
margin: 7em auto;
width: 30%;
font-family: 'Helvetica';
}
div.field {
padding-top: 2em;
border-bottom: 1px solid black;
}
button {
margin: 2em auto;
width: 100%;
padding: 1em;
cursor: pointer;
background: none;
}
button:hover {
background-color: #444444;
color: #fff;
}
label {
display: none;
}
input,
select {
outline: none;
border: none;
width: 100%;
background: none;
}
select {
color: red;
}
.success-select {
color: green;
}
select:focus {
outline: none;
border: none;
}
input {
margin-bottom: 10px;
}
/* Styling the placeholders */
input::-webkit-input-placeholder {
color: #2f3238;
font-weight: bold;
}
.failure-select{
font-weight:bold;
-webkit-animation: blinkRed 500ms 3;
animation: blinkRed 500ms 3;
}
@keyframes blinkRed{
0%{
color:black;
}
50%{
color:red;
}
100%{
color:black;
}
}
@-webkit-keyframes blinkRed{
0%{
color:black;
}
50%{
color:red;
}
100%{
color:black;
}
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span><a href="http://ryanscherf.net">Ryan Scherf's</a> contact form served as inspiration- so I decided to recreate it with a small jquery update on the select tag.</span>
<form>
<div class="field">
<label>Name</label>
<input type="text" placeholder="Name" class="name-field">
</div>
<div class="field">
<label>Email</label>
<input type="text" placeholder="Email" class="email-field">
</div>
<div class="field">
<label>Service</label>
<select id="select">
<option>Select</option>
<optgroup label="Type of Service">
<option>Service-One</option>
<option>Service-Two</option>
</optgroup>
<optgroup label="Type of Service">
<option>Service-Three</option>
<option>Service-Four</option>
</optgroup>
</select>
</div>
<div class="field">
<label>Project Description</label>
<input type="text" placeholder="Project Description" class="project-field">
</div>
<button>Submit</button>
</form>
&#13;