js程式碼實現倒數計時秒殺的效果

樹祥發表於2017-02-21

實際專案中,需求一個倒數計時秒殺功能,每天下午6點後,計算距離第二天上午10點的小時、分鐘、秒數,計時到第二天上午10點後開啟搶購功能;程式碼如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script src="js/jquery-1.11.1.min.js"></script>
	</head>
	<body onload="leftTimer();">
		<p class="tit_right" style="">
		  <span id="h" style="">00</span>
		  <span id="m" style="">00</span>
		  <span id="s" style="">00</span>
		</p>
		<p style="" id="juli"></p>
<script>													
	function leftTimer(year,month,day,hour,minute,second){ 
		var newDate = new Date();
		var newDate1 = new Date(year,month-1,day,hour,minute,second);
		var leftTime = (new Date(year,month-1,day,hour,minute,second)) - (new Date()); //計算剩餘的毫秒數 
		var days = parseInt(leftTime / 1000 / 60 / 60 / 24 , 10); //計算剩餘的天數
		var hours = parseInt(leftTime / 1000 / 60 / 60 % 24 , 10); //計算剩餘的小時 
		var minutes = parseInt(leftTime / 1000 / 60 % 60, 10);//計算剩餘的分鐘 
		var seconds = parseInt(leftTime / 1000 % 60, 10);//計算剩餘的秒數 
		if (seconds<0) {
		    $(".tit_right").css('display', 'none');
		    $("#juli").text("開始搶購");
		} 
		else{
		    days = fix(days,2); 
		    hours = fix(hours,2); 
		    minutes = fix(minutes,2); 
		    seconds = fix(seconds,2);	
			setTimeout("leftTimer(2017,2,21,11,0,0)",1000);  
			document.getElementById("h").innerHTML=hours;
			document.getElementB
			
			
			yId("m").innerHTML=minutes;
			document.getElementById("s").innerHTML=seconds;
		}
 	}
	//fix函式:將1~9的1位數轉換成01~09的格式
	function fix(num, length) {
	    return ('' + num).length < length ? ((new Array(length + 1)).join('0') + num).slice(-length) : '' + num;
	}
</script>
</body>
</html>
以上,在leftTimer() 函式裡傳參,引數為指定的日期和時間,計時就開啟了!

相關文章