入门

监控属性

使用内置绑定

控制文本和外观

绑定逻辑控制

处理表单属性

解析模板

高级应用

插件

更多信息

style 绑定

目的

style 绑定是添加或删除一个或多个DOM元素上的style值。比如当数字变成负数时高亮显示,或者根据数字显示对应宽度的Bar。

The style binding adds or removes one or more style values to the associated DOM element. This is useful, for example, to highlight some value in red if it becomes negative, or to set the width of a bar to match a numerical value that changes.

(注:如果你不是应用style值而是应用CSS class的话,请参考 css 绑定。)

(Note: If you don’t want to apply an explicit style value but instead want to assign a CSS class, see the css binding.)

例子

  1. <div data-bind="style: { color: currentProfit() < 0 ? 'red' : 'black' }">
  2. Profit Information
  3. </div>
  4. <script type="text/javascript">
  5. var viewModel = {
  6. currentProfit: ko.observable(150000) // Positive value, so initially black
  7. };
  8. viewModel.currentProfit(-50); // Causes the DIV's contents to go red
  9. </script>

currentProfit 小于0 的时候div的style.color红色,大于的话是黑色

This will set the element’s style.color property to red whenever the currentProfit value dips below zero, and to black whenever it goes above zero.

参数

  • 主参数

该参数是一个JavaScript对象,属性是你的style的名称,值是该style需要应用的值。

You should pass a JavaScript object in which the property names correspond to style names, and the values correspond to the style values you wish to apply.

你可以一次设置多个style值。例如,如果你的view model有一个叫isServre的属性,

You can set multiple style values at once. For example, if your view model has a property called isSevere,

如果参数是监控属性observable的,那随着值的变化将会自动添加或者删除该元素上的style值。如果不是,那style值将会只应用一次并且以后不在更新。

If your parameter references an observable value, the binding will update the styles whenever the observable value changes. If the parameter doesn’t reference an observable value, it will only set the styles once and will not update them later.

你可以使用任何JavaScript表达式或函数作为参数。KO将用它的执行结果来决定是否应用或删除style值。

As usual, you can use arbitrary JavaScript expressions or functions as parameter values. KO will evaluate them and use the resulting values to detemine the style values to apply.

  • 其他参数

注:应用的style的名字不是合法的JavaScript变量命名

如果你需要应用 font-weight 或者 text-decoration 或者text-decoration,你不能直接使用,而是要使用style对应的 JavaScript 名称。 例如,

If you want to apply a font-weight or text-decoration style, or any other style whose name isn’t a legal JavaScript identifier (e.g., because it contains a hyphen), you must use the JavaScript name for that style. For example,

  • 错误 { font-weight: someValue }; 正确 { fontWeight: someValue }
  • 错误 { text-decoration: someValue }; 正确 { textDecoration: someValue }
  • Don’t write { font-weight: someValue }; do write { fontWeight: someValue }
  • Don’t write { text-decoration: someValue }; do write { textDecoration: someValue }

参考:style名称和对应的JavaScript 名称列表

依赖性

除KO核心类库外,无依赖。

(c) knockoutjs.com