javascript - 在复选框更改实现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>
解决方案
编辑:设置onChipAdd
和onChipDelete
事件以在添加或删除芯片时更改颜色。
我会在没有 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>
推荐阅读
- c# - 威胁已经被清除了。@System.IO.File.InternalReadAllBytes(字符串路径,布尔检查主机)
- localization - TYPO3 定位器扩展 - 购物车配置
- javascript - 缓冲区 TurfJS 的传单控制层
- javascript - 如果用户点击外部,我如何隐藏我的下拉菜单
- typescript - 实现接口的对象中函数语法的 typescript/eslint 规则
- sql - 仅获取满足条件的前 N 行,但保留不满足条件的行
- java - 拦截 Spring Cloud Stream 目标绑定以动态修改生产者属性
- asp.net - ASP .NET Core 发布错误 AddDbContext
- java - RatingBar DialogFragment 关闭后,Android 应用程序崩溃
- python - 检测输入是否指定 discord.py