【问题标题】:Change CSS property of element when time changes当时间改变时改变元素的 CSS 属性
【发布时间】:2015-12-23 17:46:31
【问题描述】:

我正在使用流星构建一个玩具作业调度系统。

这是我传递“班次”集合的控制器:

angular.module('eamorr').controller('EamorrCtrl', ['$scope', '$meteor', function ($scope, $meteor) {
    $scope.shifts = $meteor.collection(Shifts);
    ...
}]);

...给我的.ng.html:

<tr ng-repeat="shift in shifts">
   ...
   <td>{{shift.unixTime_start*1000 | date:'yyyy-MM-dd'}}</td> 
   ...
</tr>

现在,当shift.unixTime_start 小于当前时间时,我希望整行具有background-color:orange,而当shift.unixTime_start 大于当前时间时,我希望整行具有background-color:green。

谁能给我一个提示,告诉我如何整洁、干净和简洁地做到这一点?

我一直在考虑执行大量 ng-if 语句等。我是否必须使用间隔?每 5 秒检查一次并相应地更新表格?这对我来说似乎不是正确的方式......

【问题讨论】:

  • 我会在控制器中执行此操作。添加一个新的 $scope 函数 getStyle(shift),它在控制器中进行检查,并在 html 中将返回值设置为 td 元素的样式标记。

标签: javascript angularjs meteor


【解决方案1】:

不一定。

Template.shifts.onCreated(function () {
  this.now = new ReactiveVar(moment());
  this.timerId = null;

  let oneSecond = moment().add(1, 'minute').startOf('minute');
  Meteor.setTimeout(() => {
    this.timerId = Meteor.setInterval(() => {
      this.now.set(moment());
    }, 5000)
  }, oneSecond.get('milliseconds'));
});

Template.shifts.helpers({
  timeColor: function (unix) {
    let time = moment(unix);
    if (moment.isBefore(time, this.now.get())) {
      return '#FF00FF';
    } else if (moment.isAfter(time, this.now.get())) {
      return '#FF0000';
    } else {
      return '#003366';
    }
  }
});

Template.shifts.onDestroyed(function () {
  Meteor.clearInterval(this.timerId);
})

然后在你的模板中

<tr style="background-color: {{ timeColor shift.unixTime_start }};">
  <td>{{ shift.unixTime_start }}</td>
</tr>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-24
    • 2022-08-15
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多