敲门风格绑定不让我追加!重要

时间:2015-10-19 19:03:34

标签: knockout.js data-binding

我正在尝试将背景绑定到表格单元格,如下所示:

data-bind="style: { background: Css }

Css变量可以等于#F7C7D4等颜色。

此部分有效,并且单元格中填充了颜色,但是当我尝试打印页面时,没有任何颜色显示。当我尝试没有绑定时,这样:

<td style="background #F7C7D4 !important;"></td>

页面上和打印时显示颜色。但是当我将代码更改为:

data-bind="style: { background: Css + ' !important' }

淘汰不会数据绑定背景。不会抛出错误,但屏幕上没有显示颜色,当我检查元素时,背景样式尚未添加到样式属性中。我也尝试更改Css变量以包含!important,其结果与绑定不起作用相同。

JSFiddle

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:5)

您可以使用data-bind="attr:{ style: 'background: ' + Css() + ' !important' } 绑定来设置样式属性的值)

{{1}}

答案 1 :(得分:2)

样式绑定不支持

!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' : '');
        });
    }
};