angularjs - 根据一天中的时间更改背景 DIV

标签 angularjs ionic-framework

我所有的问题都在标题中:如何根据一天中的时间更改我的背景 DIV?

我尝试了传统的 Javascript :

var d = new Date(event.starthourid),
    h = d.getHours(event.starthourid),
    i;

    if (h < 06) i = "night.jpg";
    else if (h < 11) i = "sunrise.jpg";
    else if (h < 18) i = "sunny.jpg";
    else if (h < 21) i = "sunset.jpg";
    else i = "night.jpg";

document.getElementById("header-item").style.backgroundImage = "url("+i+")";

但是自从我遇到 ng-classng-style 后,我知道我一直做错了。我怎样才能以“Angular”方式完成上述任务?

最佳答案

我认为在这种情况下,使用 ngClass 会更好,因此如果您想更新图像位置,则不必记住这些样式来自哪里。当然,ngClass 和 ngStyle 都是指令,因此它们是在 AngularJS 中进行 DOM 操作的正确位置,如 @daniel-beck 所述。

以下是如何使用 ngClass 的示例:

var app = angular.module('demo', []);

app.controller('MyTimeCtrl', function($scope){
    var h = new Date().getHours();
    if (h <= 18) {
      $scope.time="day";
    } else {
      $scope.time="night";
    }
  
});
.main {
  height: 100vh;
  min-height: 100px;
}
.night {
  background-color: black;
  color: white;
}
.day {
  background-color: yellow;
  color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="demo">
  <div ng-controller="MyTimeCtrl" class="main" ng-class="time">
    <p>It's {{time}}!</p>
  </div>
</div>

关于angularjs - 根据一天中的时间更改背景 DIV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31247454/

相关文章:

angularjs - 为什么要给 "abstract: true"状态一个 url?

javascript - 如何在 Karma 测试中模拟 POST

Angular6/MD PWA 对比 Ionic 3 + Angular 6 PWA

javascript - 尝试更改位置以使用 Google Street View Static API 捕获静态图像

angular - <ion-icon> Ionic 4 - Angular 7 中的 fontawesome 集成

javascript - window.location.href 不工作,为什么不呢?

html - 如何使 div 的高度动态适应包含它的 div 的大小?

ios - 找不到模块 : './app.module.ngfactory' i while build iOS app --prod --release

c# - 在 MVC 中出现 "Self referencing loop detected"错误

angularjs - 如何使 ionic 列表可滚动?