商品限货抢购小插件封装

<!doctype html> 
<html> 
<head> 
<meta charset="utf-8">
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script src="angular.min.js" type="text/javascript" charset="utf-8"></script>
</head> 
<body ng-app='app' ng-controller='controller'> 
<div id="CountMsg" class="HotDate" ng-repeat='x in testArray'> 
	<h4>{{x.apperTime}}</h4>
</div> 
<script type="text/javascript">
	var app=angular.module('app',[]);
	app.service('get_Rtime',function(){
					this.getTime=function(overTime){      //overtime为截至时间,时间格式:2017-08-15 23:23:23
						var obj=new Object();
						var EndTime= new Date(overTime);
						var NowTime = new Date(); 
						var t =EndTime.getTime() - NowTime.getTime();
						obj.timeStatue=t >= 0 ? 1:0;            //当时间截至时间与开始时间戳相减为正则返回1,为负返回0,用来判断是否开抢。当为0是开抢,则在判断里做开抢样式和开抢行为的实现。
						var d=Math.floor(Math.abs(t)/1000/60/60/24); 
						var h=Math.floor(Math.abs(t)/1000/60/60%24); 
						var m=Math.floor(Math.abs(t)/1000/60%60); 
						var s=Math.floor(Math.abs(t)/1000%60);
						obj.relTime=d + " 天 "+h + " 时 "+m + " 分 "+s + " 秒 ";
						return obj;
					};
					this.format = function(shijianchuo){   //时间戳转为 时间格式 2017-09-10 23:23:23
						var time = new Date(shijianchuo);
						var y = time.getFullYear();
						var m = time.getMonth()+1;
						var d = time.getDate();
						var h = time.getHours();
						var mm = time.getMinutes();
						var s = time.getSeconds();
						function add0(m){return m<10?'0'+m:m ;}
						return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s);
					};
				})
	app.controller('controller',function(get_Rtime,$scope){	
		$scope.testArray=[{overTime:'2017-8-8 23:34'},{overTime:'2017-8-20 23:35'}];
		$scope.testArray.forEach(function(value,index){
			$scope.testArray[index].setInter=setInterval(function(){
				$scope.$apply(function(){
					if(get_Rtime.getTime($scope.testArray[index].overTime).timeStatue == 1){  //判断是否开抢,开抢则显示已经开抢多长时间。
						$scope.testArray[index].apperTime='距抢购:' + get_Rtime.getTime($scope.testArray[index].overTime).relTime;
					}else{
						$scope.testArray[index].apperTime='已开抢:' + get_Rtime.getTime($scope.testArray[index].overTime).relTime;
					}
				});
			},1000);  //定时1s,虽然执行代码有时间误差,但用户不可能一直停留在这个页面,所造成的误差并不是很大。
		});
		
	});
 
</script> 
</body> 
</html>

  

原文地址:https://www.cnblogs.com/changyaoself/p/7382907.html