如何指定两个CSS类:来自属性和条件类 [英] How specify two css classes: from property and conditional class

查看:62
本文介绍了如何指定两个CSS类:来自属性和条件类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在淘汰赛中,可以从可观察的属性中指定类,如下所示:

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

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

Knockout还提供了如下指定条件类渲染的功能:

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

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

但是,如果我需要将剔除CSS绑定在一起的那些功能,应该指定哪个标记?

我尝试了这个,但是没有运气:

I tried this, but with no luck:

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

我遇到了错误:

错误:无法解析绑定. SyntaxError:意外令牌;;

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

我没有在Google或官方文档中找到任何示例.

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

更新

我找到了一种解决方法:像这样在代码中构建样式字符串并将其放入属性中,

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));

并在html中指定此类:

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?

推荐答案

使用类绑定

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

查看模型:

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

这篇关于如何指定两个CSS类:来自属性和条件类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆