最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Applying a % style binding with knockout via function not working - Stack Overflow

programmeradmin1浏览0评论

I want to set the width of a div equal to a percentage calculated by a javascript method. I can get knockout to apply the style binding properly using this:

<div class="bar" data-bind="style: { width: '50%'}"></div>

but when I try to use a function to generate the output, it breaks:

<div class="bar" data-bind="style: { width: function(){return '50' + '%';}}"></div>

I want to set the width of a div equal to a percentage calculated by a javascript method. I can get knockout to apply the style binding properly using this:

<div class="bar" data-bind="style: { width: '50%'}"></div>

but when I try to use a function to generate the output, it breaks:

<div class="bar" data-bind="style: { width: function(){return '50' + '%';}}"></div>
Share Improve this question asked Sep 19, 2013 at 18:39 jokuljokul 1,3391 gold badge16 silver badges39 bronze badges 1
  • Thanks for this! Was hoping to see a percentage example from the knockout.js docs but didn't see one anywhere. – heyitsalec Commented Jan 29, 2020 at 19:55
Add a comment  | 

5 Answers 5

Reset to default 6

It turns out you can get it to work with an anonymous function, you just need to explicitly call that function:

<div data-bind="style: { width: function(){ return '50%'; }() }"></div>

It looks like it won't take an anonymous function, but if you define the function as a named, method, I got it to work.

<script>
calcWidth = function(amt) {
  return amt + '%';
}
</script>

<div class="bar" data-bind="style: { width: calcWidth(50)}"></div>

Note: I only found this out by trial and error on knockout's interactive tutorial. I'm not sure if there are other factors that come into play here, but this was the best I was able to come up with.

This is working fine:

<div data-bind="style: { width: function() + '%' }"></div>

jsFiddle: http://jsfiddle.net/LkqTU/31377/

Another way to accomplish this that will also be useful if you need to apply multiple styles dynamically and you want a single function to calculate those, you can simply return a string from a function in your view model.

View:

<div data-bind="style: $root.calculateStyles() }"></div>

ViewModel:

self.calculateStyles = function (obj) { 
    // properties could also potentially be written dynamically depending on obj's state
    return { backgroundColor: '#112233', color: 'white', width: '35px' };
}
<div data-bind="style: { width: WATCHEDPERCENTAGE + '%' }"></div>
发布评论

评论列表(0)

  1. 暂无评论