根据observable更改类

时间:2016-12-22 00:53:39

标签: javascript css knockout.js

我的viewmodel中有一个名为" Rotation"的字段。如果它为0,则图像保持在0度(北)。如果它是1度,90度等等。

obeservable正在改变我期望它(按钮点击),但样式没有更新。

self.RotateLeft = function (data) {

    this.Rotation(this.Rotation + 1);
    if (this.Rotation() == 4)
        this.Rotation(0);
  //  alert(data.Rotation());

}

我的图片定义为:

<img data-bind="attr: {src: Image}, css: {north: Rotation()==0, east: Rotation()==1, south: Rotation()==2, west: Rotation()==3}" alt="text: Description" class="img-responsive">

我的css:

.north {
transform:rotate(0deg);
-ms-transform:rotate(0deg); /* IE 9 */
-webkit-transform:rotate(0deg); /* Safari and Chrome */
}
.west {
transform:rotate(90deg);
-ms-transform:rotate(90deg); /* IE 9 */
-webkit-transform:rotate(90deg); /* Safari and Chrome */
}
.south {
transform:rotate(180deg);
-ms-transform:rotate(180deg); /* IE 9 */
-webkit-transform:rotate(180deg); /* Safari and Chrome */

}
.east {
transform:rotate(270deg);
-ms-transform:rotate(270deg); /* IE 9 */
-webkit-transform:rotate(270deg); /* Safari and Chrome */
}

这是更改css类的正确方法吗?如果是这样,任何想法为什么它不旋转?

2 个答案:

答案 0 :(得分:2)

很高兴你得到了它的工作。但是考虑到这些类都是互斥的,你可能应该绑定到你想要直接应用的类的observable。它将大大简化一切。

var viewModel = {
  content: ko.observable('foobar'),
  css: ko.observable(),
  cssOptions: [ 'red', 'green', 'blue' ],
  next: function () {
    var css = viewModel.css(),
        cssOptions = viewModel.cssOptions,
        length = cssOptions.length,
        index = cssOptions.indexOf(css),
        nextIndex = index >= 0 ? index + 1 : 0;
    viewModel.css(cssOptions[nextIndex % length]);
  }
};
ko.applyBindings(viewModel, document.getElementById('main'));
.red   { color: red;   }
.green { color: green; }
.blue  { color: blue;  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div id="main">
  <div data-bind="text: content, css: css"></div>
  <div>
    <select data-bind="value: css, options: cssOptions, optionsCaption: 'css'"></select>
    <button data-bind="click: next">NEXT</button>
  </div>
</div>

答案 1 :(得分:1)

在javascript中发现错误。

this.Rotation + 1

应该是

this.Rotation() + 1

新秀错误。