我的代码如下所示
$(document).ready(function{
$('.#situation').on("click", function{
console.log('clicked');
});
});
.placeholder_color{
color: #828282;
}
<select name="situation" id="situation">
<option selected="selected">Current Situation</option>
<option class="placeholder_color" value="Unemployed">Unemployed</option>
<option class="placeholder_color" value="Employed">Employed</option>
</select>
目前,select标签的颜色正如您所见,几乎就像一个占位符。 我希望能够在单击具有类占位符的选项标记时更改文本颜色。
我该怎么做?
答案 0 :(得分:3)
您应该on change
上的select
活动而不是option
。然后找到selected
选项并检查所选选项是否包含类placeholder
。如果是,请将live
添加到select
。如果没有,请从live
select
请参阅下面的代码段
如果有帮助请告诉我
$('select').on("change", function() {
var opt = $(this).find("option:selected")
if ($(opt).hasClass("placeholder")) {
$(this).addClass("live")
} else {
$(this).removeClass("live")
}
});
&#13;
#situation {
color: #828282;
}
#situation option {
color:#828282;
}
#situation.live {
color: red;
}
select {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}
/* for IE */
select::-ms-expand {
display: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="situation" id="situation">
<option selected="selected">Current Situation</option>
<option class="placeholder" value="Unemployed">Unemployed</option>
<option class="placeholder" value="Employed">Employed</option>
<option selected="selected">Current Situation</option>
</select>
&#13;
答案 1 :(得分:0)
这将解决您的问题
jQuery(document).ready(function($) {
$('#situation').on("click", function(){
$('.placeholder').toggleClass('live');
});
});
#situation{
color: #828282;
}
.live{
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="situation" id="situation">
<option class="placeholder" value="Unemployed"> Unemployed </option>
<option class="placeholder" value="Employed"> Employed </option>
</select>
答案 2 :(得分:0)
点击选项有点棘手。您可以在选择框上使用更改触发器,但是找出占位符类可能有点困难。因此,您可以使用以下内容来满足您的需求。
$(document).ready(function() {
$('#situation').on('click', function(ev) {
if (ev.offsetY < 0) {
//user clicks on option
$(this).toggleClass("live");
}
});
});
&#13;
#situation, #situation option {
color: #828282;
}
#situation.live {
color: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="situation" id="situation">
<option selected="selected">Current Situation</option>
<option class="placeholder" value="Unemployed">Unemployed</option>
<option class="placeholder" value="Employed">Employed</option>
</select>
&#13;