我正在尝试使用 AngularJS 中的 $interval
服务来来回闪烁文本的颜色(红到黑)。以下代码不起作用,我不知道为什么。
这是 HTML(这个问题针对 span 部分)。
<div class="jumbo" ng-mouseenter="myStyle = {'background-color':'gold'}" ng-mouseleave="myStyle ={'background-color':''}">
<h1 ng-style="myStyle">Sanjay Kumar Technology Services <span class="iflash" ng-style ="{{textColor}}">(NodeJS & AngularJS Demo)</span></h1>
</div>
这是 .js 文件中的 AngularJS:
(function () {
var app = angular.module("SanjayPage", []);
var MainController = function ($scope, $http, $interval) {
$scope.textColor = "{'color': 'black'}";
var change = 1;
var flash = function () {
if (change === 1) {
$scope.textColor = "{'color': 'red'}";
change = 2;
}
else {
$scope.textColor = "{'color': 'black'}";
change = 1;
}
};
var colorFlash = function () {
$interval(flash, 1000);
};
colorFlash();
};
app.controller("MainController", ["$scope", "$http", "$interval", MainController]);
}());
如果我将 $interval(flash, 1000);
更改为 $interval(flash(), 1000);
那么我可以让它运行一次并更改颜色黑色至红色。但间隔不会重复。我错过了什么?
最佳答案
您不需要 Angular 或 $interval 来显示闪烁的文本。您可以使用 CSS 来做到这一点。
@-webkit-keyframes flash {
from {color: red;}
to {color: black;}
}
.flash{
-webkit-animation-name: flash;
-webkit-animation-duration: 1s;
-webkit-animation-iteration-count:infinite;
-webkit-animation-timing-function:ease-in-out;
-webkit-animation-direction: alternate;
}
http://codepen.io/mchambaud/pen/VvvKrK
根据 CANIUSE.com,这应该适用于大多数浏览器。
http://caniuse.com/#feat=css-animation
更新:使用 AngularJS $interval
HTML
<div class="jumbo"
ng-controller="MainController"
ng-mouseenter="backgroundColor = 'background-gold'"
ng-mouseleave="backgroundColor = ''">
<h1 ng-class="backgroundColor">
Sanjay Kumar Technology Services
<span ng-class="color">
(NodeJS & AngularJS Demo)
</span>
</h1>
</div>
CSS
.red {
color:red;
}
.black {
color:black;
}
.background-gold {
background-color:gold;
}
JavaScript
var app = angular.module("SanjayPage", []);
var MainController = function ($scope, $http, $interval) {
$scope.backgroundColor = '';
$scope.color = 'black';
$interval(function (i) {
$scope.color = i % 2 ? 'red' : 'black';
}, 1000);
};
app.controller("MainController", ["$scope", "$http", "$interval", MainController]);
关于javascript - AngularJS 使用 $interval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32503214/