首页 技术 正文
技术 2022年11月15日
0 收藏 342 点赞 3,500 浏览 1829 个字

4. css绑定

目的

css绑定可以给关联的DOM元素添加或移除一个或多个CSS类。该绑定很有用,比如,当一些值为负数时高亮这些值为红色。

(注意:如果你不想使用一个CSS类选择器来附加样式而想直接给style属性赋值,请看style绑定。)

静态类样式例子

<div data-bind="css: { profitWarning: currentProfit() < 0 }">
Profit Information
</div><script type="text/javascript">
var viewModel = {
currentProfit: ko.observable(150000) // Positive value, so initially we don't apply the "profitWarning" class
};
viewModel.currentProfit(-50); // Causes the "profitWarning" class to be applied
</script>

currentProfit 的值小于0的时候,会应用样式profitWarning ,当值大于0的时候,会移除该类选择器样式。

动态类样式例子

<div data-bind="css: profitStatus">
Profit Information
</div><script type="text/javascript">
var viewModel = {
currentProfit: ko.observable(150000)
}; // Evalutes to a positive value, so initially we apply the "profitPositive" class
viewModel.profitStatus = ko.pureComputed(function() {
return this.currentProfit() < 0 ? "profitWarning" : "profitPositive";
}, viewModel); // Causes the "profitPositive" class to be removed and "profitWarning" class to be added
viewModel.currentProfit(-50);
</script>

currentProfit 的值为正数时,会应用profitPositive 样式,否则会应用profitWarning 样式。

参数

  • 主参数

    如果你想使用静态类名,你可以传入一个javascript对象,其属性是你的CSS类名,它们的值会计算为truefalse来决定类选择器样式是否应用。

    你可以一次设置多个CSS类样式,比如,你的视图模型有一个叫isSevere的属性。

<div data-bind="css: { profitWarning: currentProfit() < 0, majorHighlight: isSevere }">

你甚至可以基于一些条件来设置多个CSS样式,只要样式名被引号包裹起来。

<div data-bind="css: { profitWarning: currentProfit() < 0, 'major highlight': isSevere }">

非布尔值会被试图转换为布尔值。比如,0null会被看做false,而21和非空对象会被看做true

如果你的参数引用了一个监控值,当监控值发生改变时,CSS类会根据条件添加或移除。如果参数没有引用监控值,它只会在第一次添加或移除样式,之后不会这样做。

如果你想使用动态CSS类名,你可以传入一个字符串,字符串包含你想要加到元素上的类名。如果参数引用了一个监控值,绑定会移除旧值,然后添加对应的类名作为监控对象的新值。

通常情况下,你可以任意javascript表达式或函数作为参数值。KO会计算它们然后用结果值来决定CSS样式的增删。

  • 额外参数

注意:应用不合法的javascript变量名的css样式类名

如果你想应用样式my-class,你不能这样写:

<div data-bind="css: { my-class: someValue }">...</div>

因为my-class不是一个合法的变量标识符。解决办法很简单,只要用引号把标识名包括起来,这样变成了一个字面量,javascript对象字面量是合法的。比如:

<div data-bind="css: { 'my-class': someValue }">...</div>

依赖

只有核心KO库

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,116
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,588
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,433
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,204
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,840
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,925