如果选择了选项,则更改选择元素的不透明度

时间:2015-11-07 06:57:19

标签: javascript jquery css

我有多个像这样的选择元素:

<li>
    <select>
        <option>select something</option>
        <option value="1">something</option>
        <option value="2">anything</option>
    </select>
</li>
<li>
    <select>
        <option>select something</option>
        <option value="1">something</option>
    </select>
</li>
<li>
    <select>
        <option>select something</option>
        <option value="1">something</option>
    </select>
</li>

现在我需要在页面加载后为每个具有选定选项的select元素将不透明度更改为0.5。我不太确定这是否可以通过纯CSS完成,所以我尝试用JQuery做到这一点:

$('select').each(function(select) {
    $('select option').each(function() {
        if($(this).is(':selected')) {
            select.css({ opacity: 0.5 });
        }
    });
});

但这不正确,因为它不起作用。

3 个答案:

答案 0 :(得分:3)

您需要使用change个活动,而不是两个.each

&#13;
&#13;
function isNotEmpty(element) {
  return ($('option:selected', element).attr('value') || '').length;
}

$('select').on('change mouseout',function () {
  $(this).css({ opacity: isNotEmpty(this) ? 0.5 : 1 });
}).on('mouseover', function () {
  $(this).css({ opacity: 1 })
}).change();
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>
    <select>
      <option>select something</option>
      <option value="1">something</option>
      <option value="2">anything</option>
    </select>
  </li>
  <li>
    <select>
      <option>select something</option>
      <option value="1">something</option>
    </select>
  </li>
  <li>
    <select>
      <option>select something</option>
      <option value="1">something</option>
    </select>
  </li>
</ul>
&#13;
&#13;
&#13;

答案 1 :(得分:3)

确保为默认选项指定空值。然后只需将change事件绑定到select元素,在页面加载时触发一次(如果所选值不是默认值),并使用CSS作为悬停不透明度。

 $('select').on('change', function() {
   if (this.value) {
     $(this).css('opacity', '0.5');
   } else {
     $(this).css('opacity', '1');
   }
 }).change();
select:hover {
  opacity: 1!important
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<ul>
  <li>
    <select>
      <option value="">select something</option>
      <option value="1">something</option>
      <option value="2">anything</option>
    </select>
  </li>
  <li>
    <select>
      <option value="">select something</option>
      <option value="1" selected="selected">something</option>
    </select>
  </li>
  <li>
    <select>
      <option value="">select something</option>
      <option value="1">something</option>
    </select>
  </li>
</ul>

答案 2 :(得分:1)

$('select').each(function(select) {
    $('select option').each(function() {
        if($(this).is(':selected')) {
            $(this).parent.css('opacity', '0.5');
        }
    });
});