How specify two css classes: from property and conditional class

不羁的心 提交于 2019-12-05 13:43:01

问题


I know that in knockout has the ability to specify class from observable property, like this:

<div data-bind="css: Color " >

Knockout also provides the ability to specify conditional class rendering like this:

<div data-bind="css: { 'my-class' : SomeBooleanProperty  }" >

But which markup should be specified if i need those features of knockout css binding together?

I tried this, but with no luck:

<div data-bind="css: { Color, 'my-class' : SomeBooleanProperty  }" >

I have got the error:

Error: Unable to parse bindings. SyntaxError: Unexpected token ,;

I not found any example in google or in official docs.

UPDATE

I found a workaround: build up style string in code and put it to property, like this:

item.AdditionalCss(Color() + " " + (result.IsSortable() ? 'my-class' : null));

And specify this class in html:

data-bind="css: AdditionalCss "

But i little bit puzzled, i think it is dirty approach. I think it would be better to achieve the same result in markup. How can accomplish that with markup?


回答1:


Use the class binding

<div data-bind="class: myClass" >

View model :

var vm = {
     myClass : ko.observableArray(),
};
vm.myClass.push('class1');
vm.myClass.push('class2');

You can also use the class binding with a computed.

But if you don't want to use it, you can do that :

<div data-bind="attr: { 'class' :( Color() +  (SomeBooleanProperty() ? ' my-class' :'')) }">



回答2:


You can also use a classic string formatting :

<div data-bind="css: Color() + (SomeBooleanProperty ? ' my-class' : '')" >

An example of this concept in action:

var fullString = ('some' + ' ' + 'strings ') + 'and' + ' ' + 'other strings';
console.log(fullString);


来源:https://stackoverflow.com/questions/17918300/how-specify-two-css-classes-from-property-and-conditional-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!