javascript - 在knockout js中动态改变一条线的颜色

标签 javascript jquery css knockout.js

我有一个 css 类可以画这样一条线:

.divider {
  border-top: 1px solid;
  border-top-color: #000;
}

现在每次绘制这个分隔线时,我都想动态改变颜色。我在 div 元素上使用样式绑定(bind),如下所示:

<div class="divider" data-bind="style: { border-top-color: $data.color }"></div>

但不知何故颜色没有改变。我得到这个错误:

knockout.js?body=1:2937 Uncaught SyntaxError: Unable to parse bindings.
Bindings value: style: { border-top-color: $data.color }
Message: Unexpected token -

正确的做法是什么?

最佳答案

您不能使用带有连字符的样式,因为它不是有效的 JavaScript 标识符。 Knockout documentation ,部分 注意:应用名称不是合法 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,

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

See also: a longer list of style names and their JavaScript equivalents

所以在你的情况下而不是

<div class="divider" data-bind="style: { border-top-color: $data.color }"></div>

你应该使用

<div class="divider" data-bind="style: { borderTopColor: $data.color }"></div>

关于javascript - 在knockout js中动态改变一条线的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36685166/

相关文章:

javascript - 将数据保存为对象还是数组?

javascript - 圆滑的显示一个在中心

javascript - jQuery 中的随机颜色

html - 无法将我的 css 文件链接到 html

html - 如何让 overflow-x 滚动条出现在位置为 : absolute? 的 <div> 内的 <ul> 上

javascript - 递归 .children() 以搜索 id 属性

javascript - 保护我的私有(private) API

javascript - JQuery DataTables 和 ColVis 插件错误 "Cannot read property ' sWidth' of undefined"

javascript - youtube iframe api在另一个正在播放时停止视频

javascript - 我如何使这样的代码在添加到列表中的每个元素之间有中断?