首页 > 解决方案 > 在复选框更改实现css时更改芯片颜色

问题描述

我在网上搜索过,我无法解决我的问题。

我正在使用Material CSS芯片,我想要的是,每当检查复选框时,最后芯片的颜色应更改为绿色,而其他芯片的颜色则变为红色,如果不选中,它们都会变成红色。

我不知道这是否可能,因为我已经设定了条件

$('.chips-placeholder').chips({
    placeholder: 'Enter options',
    secondaryPlaceholder: '+Options',
    limit:6
});

$(document).ready(function() {
    $('#anscheck').change(function() {
        if($("#anscheck").is(":checked")){

        }    
    });
});

html

                   <div class="row opt">
                       <div class="col m4 s10 offset-m3 chips-placeholder">
                           <input type="text" name="opts[]">
                       </div>
                       <div class="col m4 s10 switch correctans">
                        <label>
                          Off
                          <input type="checkbox" id='anscheck'>
                          <span class="lever"></span>
                          On
                        </label>
                       </div>
                   </div> 

标签: javascriptjquerycssmaterialize

解决方案


编辑:设置onChipAddonChipDelete事件以在添加或删除芯片时更改颜色。

我会在没有 jQuery 方法的情况下初始化芯片组件。

1) 获得所有筹码。

$(chipInstance[0].$chips)

2) 循环遍历所有筹码,检查筹码的(index+1)是否等于所有筹码的个数。(原因索引是从零开始的。)

allChips.each(function(index, element){
  let Color = (index+1) == allChips.length ? 'green' : 'red';
  $(element).addClass(Color)
})

3)添加类以更改字体颜色。

这是一个演示:

let target = $('.chips-placeholder');
let options = {
  placeholder: 'Enter options',
  secondaryPlaceholder: '+Options',
  limit: 6,
  onChipAdd: function(){
    CheckChipsColor();
  },
  onChipDelete: function(){
    CheckChipsColor();
  }
}

let chipInstance = M.Chips.init(target, options)

$('#anscheck').change(function() {
  CheckChipsColor();
});

function CheckChipsColor(){
  let allChips = $(chipInstance[0].$chips);
  allChips.removeClass('red green');
  if ($("#anscheck").is(":checked")) {
    allChips.each(function(index, element){
      let Color = (index+1) == allChips.length ? 'green' : 'red';
      $(element).addClass(Color)
    })
  }
}
.red{
  color: red;
}

.green{
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css" />

<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.js"></script>

<div class="row opt">
  <div class="col m4 s10 offset-m3 chips-placeholder">
    <input type="text" name="opts[]">
  </div>
  <div class="col m4 s10 switch correctans">
    <label>
    Off
      <input type="checkbox" id='anscheck'>
      <span class="lever"></span>
    On
    </label>
  </div>
</div>


推荐阅读