简体   繁体   中英

How can I add a “clicked” condition in knockout.js css-binding?

The documentation of css-binding in knockout.js provides an example as follows:

<div data-bind="css: { profitWarning: currentProfit() < 0 }">
   Profit Information
</div>

  <script type="text/javascript">
   var viewModel = {
    currentProfit: ko.observable(150000) // Positive value, so initially we don't apply the "profitWarning" class
};
   viewModel.currentProfit(-50); // Causes the "profitWarning" class to be applied
</script>

It seems like this example applies the "profitWarning" currentProfit is negative. I want to change this a bit, and apply this class when the div is clicked. How can I apply the "clicked" condition to this example? Also, I want to make multiple divs and apply the style only one at a time (apply the style when a div is clicked and remove it when another div is clicked)

Thanks

You can use click binding.

The click binding adds an event handler so that your chosen JavaScript function will be invoked when the associated DOM element is clicked. This is most commonly used with elements like button, input, and a, but actually works with any visible DOM elemen

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

Here is an example:

 function viewModel() { var self = this; self.isSelected = ko.observable(false); self.className = ko.pureComputed(function(){ return self.isSelected()? "SelectedClass" : "NotSelectedClass"; }, self); self.change = function() { self.isSelected(!self.isSelected()); } } ko.applyBindings(new viewModel()); 
 <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 data-bind="text: className"></div> <br/> <div data-bind="css: className">Inspect this Div</div> <br/> <input type="button" data-bind="click: change" value="Toggle" /> 

For your second question, you can provide couple of boolean for each of the div to check which one is clicked, set the one clicked by user to true then set the rest to false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM