Knockout js CSS绑定

时间:2017-05-19 13:41:16

标签: css3 knockout.js knockout-2.0

我在我的项目中使用Knockout js,我需要为特定标签添加多个css类名。我是我的代码我有三个不同的类我怎么能在敲除css绑定中添加它善意建议。

<img data-bind="attr: { src:ProfileImageSrcName }" class="tabUser profile-Image tabpic" />

2 个答案:

答案 0 :(得分:3)

你可以如下css绑定。

&#13;
&#13;
var vm = {
  profileImageSrcName: ko.observable('http://cumbriaskills.wdfiles.com/local--files/files:images/metro_128_chrome.png'),
  isProfilePic: ko.observable(true),
  isTab: ko.observable(true),
  toggleProfile: function() { vm.isProfilePic(!vm.isProfilePic()); },
  toggleTab: function() { vm.isTab(!vm.isTab()); }
};

ko.applyBindings(vm);
&#13;
.tabUser { width: 100px; height: 100px; object-fit: contain; }
.profile-image { border-radius: 100% } 
.tabPic { box-shadow: 0 2px 6px rgba(0,0,0,0.4) }
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<img data-bind="attr: { src: profileImageSrcName }, 
                css: { 
                  'profile-image': isProfilePic, /* single class */
                  'tabUser tabPic': isTab  /* multiple classes */
                }" />
<br><br>
<button data-bind="click: toggleProfile">Toggle "profile-image" Class</button><br>
<button data-bind="click: toggleTab">Toggle "tabUser" and "tabPic" Classes</button>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

使用css绑定指定多个类名。

http://knockoutjs.com/documentation/css-binding.html

var masterVM = (function () {
  var self = this;      
  self.classNames = ko.pureComputed(function(){
    return "className1 className2 className3";
  }, self);
})();

ko.applyBindings(masterVM); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div class="existingClass" data-bind="css: classNames">
  Inspect this element to see list of the 4 class names.
</div>