How to use the style data bindings?

2019-04-07 15:52发布

I'm having difficulties getting the style binding working in 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> 

The result of rendering this template is:

<div id="avatar_1" class="avatar" style="width: 50px; height: 85px;">avatar.png, 0, 0</div> 

Can anyone help me figure out why all styles which are dependent on the view model do not show up?

标签: knockout.js
2条回答
戒情不戒烟
2楼-- · 2019-04-07 16:29

This is not a direct answer but I googled onto this page while investigating. I had something like this:

<div data-bind="style: { backgroundImage: src }">

where src is a value in my model object like "http://image.com/foo.jpg". Specifying src as a function as in the above answer did not help:

<div data-bind="style: { backgroundImage: src() }">

I found that if the src value is not a valid background-image property, it is completely ignored.

I had to use:

<div data-bind="style: { backgroundImage: 'url(\'' + src() + '\'' }">

Might save someone some pain at some point :)

查看更多
▲ chillily
3楼-- · 2019-04-07 16:31

If x and y are observables, then you need to specify it like this:

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

If you use an observable in an expression, then it needs to be specified with (), as it won't get unwrapped automatically.

http://jsfiddle.net/rniemeyer/6GtV3/

查看更多
登录 后发表回答