The knockout.js documentation shows the css binding like this:
knockout.js文档显示了这样的css绑定:
<div data-bind="css: { profitWarning: currentProfit() < 0 }">
Profit Information
</div>
I need to adapt it to change the css class on mouseclick. How can I do this?
我需要调整它来改变mouseclick上的css类。我怎样才能做到这一点?
Based on answers below, I am using some code like this:
根据下面的答案,我使用的代码如下:
// CSS class to be applied
<style>
.bigclass
{
width: 200px;
}
</style>
// Select list inside a jquery .tmpl
<script id='criteriaRowTemplate' type='text/html'>
<tr>
<td>
<select data-bind='click: makeBig, css: {bigclass : SelectHasFocus() > 0}' />
</td>
</tr>
</script>
// Knockout.js Viewmodel
var CriteriaLine = function() {
this.SearchCriterion = ko.observable();
this.SelectHasFocus = ko.observable(0);
// this method is called
makeBig = function(element) {
this.SelectHasFocus(1);
};
};
However, this is not expanding the width of the select list. What am I doing wrong?
但是,这不会扩展选择列表的宽度。我究竟做错了什么?
3 个解决方案
#1
16
Have your click function change an observable variable. For example:
让您的单击函数更改可观察变量。例如:
<div data-bind="css: { myclass: newClass() == true }">
Profit Information
</div>
<button data-bind="click: changeClass">Change Class</button>
<script type="text/javascript">
var viewModel = {
newClass: ko.observable(false),
changeClass: function() {
viewModel.newClass(true);
}
};
</script>
Note: You can combine click
and css
on the same element. For example:
注意:您可以在同一元素上组合click和css。例如:
<div databind="click: changeClass, css: { myclass: newClass() == true }"></div>
#2
1
I feel the problem is with script tag.
我觉得问题出在脚本标签上。
Please find the solution in following link: http://jsfiddle.net/ZmU6g/3/
请在以下链接中找到解决方案:http://jsfiddle.net/ZmU6g/3/
#3
1
The simplest way is to use a click binding which changes an observable in the callback. You would bind the class appropriately using something like the attr binding
最简单的方法是使用单击绑定来更改回调中的observable。您可以使用attr绑定之类的东西来适当地绑定类
#1
16
Have your click function change an observable variable. For example:
让您的单击函数更改可观察变量。例如:
<div data-bind="css: { myclass: newClass() == true }">
Profit Information
</div>
<button data-bind="click: changeClass">Change Class</button>
<script type="text/javascript">
var viewModel = {
newClass: ko.observable(false),
changeClass: function() {
viewModel.newClass(true);
}
};
</script>
Note: You can combine click
and css
on the same element. For example:
注意:您可以在同一元素上组合click和css。例如:
<div databind="click: changeClass, css: { myclass: newClass() == true }"></div>
#2
1
I feel the problem is with script tag.
我觉得问题出在脚本标签上。
Please find the solution in following link: http://jsfiddle.net/ZmU6g/3/
请在以下链接中找到解决方案:http://jsfiddle.net/ZmU6g/3/
#3
1
The simplest way is to use a click binding which changes an observable in the callback. You would bind the class appropriately using something like the attr binding
最简单的方法是使用单击绑定来更改回调中的observable。您可以使用attr绑定之类的东西来适当地绑定类