根据一天的时间变化的背景DIV根据、背景、时间、DIV

2023-09-13 05:20:50 作者:伪善

我所有的问题是在标题:我怎么能根据每天的时间而改变我的背景DIV

我试过传统JavaScript:

 变种D =新的日期(event.starthourid)    H = d.getHours(event.starthourid)    一世;    如果(H&下; 06)I =night.jpg;    否则如果(H&下; 11)I =sunrise.jpg;    否则如果(H&下; 18)I =sunny.jpg;    否则如果(H&下; 21)I =sunset.jpg;    别的我=night.jpg;。的document.getElementById(头项)style.backgroundImage =URL(+ I +); 

但因为我遇到了纳克级 NG-风格,我知道我已经做错了。我怎样才能完成上述的角的方式?

解决方案

我想你会与ngClass在这种情况下提供更好的服务,所以你不必记得这些风格是从,如果你想更新即将到来例如一个图像位置。而且,当然,无论是ngClass和ngStyle的指令,所以他们做的AngularJS DOM操作正确的地方,如前所述@丹尼尔 - 贝克。

下面是如何使用ngClass一个例子:

\r\r

VAR应用= angular.module('示范',[]);\r\rapp.controller('MyTimeCtrl',函数($范围){\r    VAR H =新的日期()调用getHours()。\r    如果(H< = 18){\r      $ scope.time =天;\r    }其他{\r      $ scope.time =飞人;\r    }\r  \r}); 一个div 上下两行 如何根据考勤记录把上下班时间分成2列并算加班时长...

\r

。主要{\r  高度:100vh;\r  最小高度:100像素;\r}\r。晚上{\r  背景色:黑色;\r  颜色:白色;\r}\r。天 {\r  背景色:黄色;\r  颜色:黑色;\r}

\r

&LT;脚本SRC =htt​​ps://ajax.googleapis.com/ajax /libs/angularjs/1.2.23/angular.min.js\"></script>\r&LT; D​​IV NG-应用=演示&GT;\r  &LT; D​​IV NG控制器=MyTimeCtrl级=主NG-CLASS =时间&GT;\r    &LT; P&gt;其是{{时间}}&LT;!/ P&GT;\r  &LT; / DIV&GT;\r&LT; / DIV&GT;

\r\r\r

All my question is in the title: How can I change my background DIV depending on the time of day?

I tried traditional 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+")";

But since I encountered ng-class and ng-style, I understand I've been doing it wrong. How can I accomplish the above the "Angular" way?

解决方案

I think you'd be better served with ngClass in this case, so you don't have to remember where those styles are coming from if you want to update an image location for example. And, of course, both ngClass and ngStyle are directives, so they are the right place to do DOM manipulation in AngularJS, as stated @daniel-beck.

Here's an example of how to use 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>