我很难弄清楚为什么当复选框被选中时,我的模板中的背景颜色样式没有得到更新。
在我的div标签中,我有:
data-bind="style: {"backgroundColor": isChecked == true ? "#00796B" : "#999"}"
我想在选中或取消选中复选框时更改div标记的背景色。现在背景颜色没有改变,但我对输入标签的检查似乎如期进行。
function checkboxViewModel(params) {
var self = this;
self.isChecked = ko.observable(params.isChecked || false);
self.isDisabled = ko.observable(params.isDisabled || false);
}
ko.components.register('material-checkbox', {
viewModel: checkboxViewModel,
template:
'<div class="checkbox" data-bind="style: {"backgroundColor": isChecked == true ? "#00796B" : "#999"}>' +
'<input type="checkbox" id="checkbox" data-bind="css: {disabled: isDisabled}, checked: isChecked, disabled: isDisabled" />' +
'<label for="checkbox"></label>' +
'</div>'
});
ko.applyBindings();
.checkbox{
width: 20px;
height: 20px;
background-color: #999;
position: relative;
border-radius: 3px;
input{
visibility: hidden;
&:checked + label{
background-color: #00796B;
&:before{
opacity: 1;
}
}
}
input.disabled{
&:checked + label{
background-color: #999;
&:before{
opacity: 1;
}
}
}
label{
width: 16px;
height: 16px;
position: absolute;
top: 2px;
left: 2px;
background-color: white;
border-radius: inherit;
&:before{
content: "";
width: 12px;
height: 6px;
border: 2px solid white;
border-top: none;
border-right: none;
position: absolute;
-webkit-transform: rotate(-45deg); /* Chrome, Safari, Opera */
transform: rotate(-45deg);
top: 2px;
left: 1px;
opacity: 0;
}
}
}
<link href="checkbox.less" rel="stylesheet/less" type="text/css" />
<script src="//cdnjs.cloudflare.com/ajax/libs/less.js/2.5.3/less.min.js"></script>
<material-checkbox params:"isChecked: false, isDisabled: false"></material-checkbox>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-debug.js"></script>
<script src="checkbox.js"></script>
您有几个拼写错误和小的语法问题,最显著的是:
isChecked == true
应该将isChecked
作为一个函数调用,因为它是可观察的。如果你想在一个复杂的表达式中使用一个可观察的,你必须使用isChecked()
。只有在更简单的场景中,您只需直接绑定到可观察对象,就可以省略括号(例如使用checked: isChecked
)- 模板中的引号被打乱了
如果你修复了这些问题,backgroundColor
绑定将正常工作:
function checkboxViewModel(params) {
var self = this;
self.isChecked = ko.observable(params.isChecked || false);
}
ko.components.register('material-checkbox', {
viewModel: checkboxViewModel,
template:
'<div class="checkbox" data-bind="style: {'backgroundColor': isChecked() == true ? '#00796B' : '#999'}">' +
'<input type="checkbox" data-bind="checked: isChecked" />' +
'</div>'
});
ko.applyBindings();
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/less.js/2.5.3/less.min.js"></script>
<material-checkbox params:"isChecked: false, isDisabled: false"></material-checkbox>