【问题标题】:How to use the style data bindings?如何使用样式数据绑定?
【发布时间】:2011-06-15 19:48:02
【问题描述】:

我在让样式绑定在 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> 

谁能帮我弄清楚为什么所有依赖于视图模型的样式都没有显示出来?

【问题讨论】:

    标签: knockout.js


    【解决方案1】:

    如果xy 是可观察的,那么你需要像这样指定它:

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

    【讨论】:

    • 啊,我想知道如何进行 KnockoutJS 连接.. 谢谢 :o)
    • 天哪!只花了 30 分钟试图弄清楚这一点! =D
    • 谢谢。也节省我的时间
    • 太棒了。我正在正确访问 x() 和 y(),但我没有想到我需要添加单位“px”。谢谢
    【解决方案2】:

    这不是一个直接的答案,但我在调查时搜索了这个页面。我有这样的事情:

    <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() + '\'' }">
    

    可能会在某个时候为某人减轻一些痛苦:)

    【讨论】:

    • 感谢您抽出宝贵时间!这正是我正在寻找的用例!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-19
    • 2015-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-21
    • 1970-01-01
    相关资源
    最近更新 更多