我很难让样式绑定在KnockoutJS中工作。
<script id="avatarTemplate" type="text/x-jquery-tmpl">
<div id="avatar_${id}" class="avatar" data-bind="style:
{ background: s, width: '50px', height: '85px', left: (x + 'px'), top:
(y + 'px') }">${s}, ${x}, ${y}</div>
</script>
<div data-bind="template: { name: 'avatarTemplate', foreach: avatars }"></div>
呈现此模板的结果为:
<div id="avatar_1" class="avatar" style="width: 50px; height: 85px;">avatar.png, 0, 0</div>
谁能帮我弄清楚为什么依赖于视图模型的所有样式都没有显示出来?
发布于 2011-06-16 04:05:03
如果x
和y
是可观察的,那么您需要这样指定它:
<div id="avatar_${id}" class="avatar" data-bind="style:
{ background: s, width: '50px', height: '85px', left: (x() + 'px'), top:
(y() + 'px') }">${s}, ${x}, ${y}</div>
如果在表达式中使用了observable,则需要使用()指定它,因为它不会自动解包。
http://jsfiddle.net/rniemeyer/6GtV3/
发布于 2016-09-28 16:49:24
这不是一个直接的答案,但我在调查时搜索到了这个页面。我有这样的东西:
<div data-bind="style: { backgroundImage: src }">
其中src
是我的模型对象中的一个值,比如"http://image.com/foo.jpg“。将src指定为上述答案中的函数无济于事:
<div data-bind="style: { backgroundImage: src() }">
我发现如果src
值不是有效的背景图像属性,它将被完全忽略。
我不得不使用:
<div data-bind="style: { backgroundImage: 'url(\'' + src() + '\'' }">
在某些情况下可能会减轻某些人的痛苦:)
https://stackoverflow.com/questions/6363405
复制相似问题