!important
不被樣式的綁定支持。一種選擇是使用css
綁定來代替並使用實際的css類。
另一種選擇是使用自定義綁定。這是樣式綁定如何應用Knockout 3.3的風格。
ko.bindingHandlers['style'] = {
'update': function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor() || {});
ko.utils.objectForEach(value, function(styleName, styleValue) {
styleValue = ko.utils.unwrapObservable(styleValue);
if (styleValue === null || styleValue === undefined || styleValue === false) {
// Empty string removes the value, whereas null/undefined have no effect
styleValue = "";
}
element.style[styleName] = styleValue;
});
}
};
關鍵部分是element.style[styleName] = styleValue;
。
設置樣式不支持!important
的這種方法。相反,使用setProperty
可以讓你「重要」,但是請注意,這隻適用於IE9 +。
element.style.setProperty('background', '#F7C7D4', 'important');
下面是這個綁定可能看起來像什麼的例子。
ko.bindingHandlers.myCustomStyleBinding = {
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor() || {});
ko.utils.objectForEach(value, function(styleName, styleValue) {
var isImportant = false;
styleValue = ko.utils.unwrapObservable(styleValue);
if (styleValue === null || styleValue === undefined || styleValue === false) {
// Empty string removes the value, whereas null/undefined have no effect
styleValue = "";
}
isImportant = styleValue.indexOf('!important') > -1;
styleValue = styleValue.split(' !important')[0];
element.style.setProperty(styleName, styleValue, isImportant ? 'important' : '');
});
}
};