js實現倒計時,其實很簡單,然而現在的公司居然一直用flash來做,太麻煩了,先寫一個倒計時天數的,一行代碼實現
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
</head>
<style type="text/css">
body {
font-size: 20px;
}
input{
font-size: 40px;
}
</style>
<script>
window.onload = function() {
var newtime = new Date(); //獲取現在日期
var endtim = new Date("2018-06-3"); //設置結束日期
var psel = $("#countdown").val(Math.ceil((endtim - newtime) / 86400000)); //計算並輸出
}
</script>
<body>
距離設定日期還有:<input type="button" name="countdown" id="countdown" value="無數據" />天
</body>
</html>
上面這個因爲是每天刷新一次,所以沒有加setInterval,下面寫一個複雜點的,可以輸入日期的倒計時
直接上代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
</head>
<style type="text/css">
body {
font-size: 20px;
padding: 100px;
}
input {
border: 0px;
background-color: rgba(0, 0, 0, 0);
font-size: 20px;
width: 200px;
}
.ipt {
font-size: 30px;
}
.djs {
border: 0px;
background-color: rgba(0, 0, 0, 0);
font-size: 20px;
width: 32px;
}
.four {
width: 70px;
}
.three {
width: 62px;
}
.two {
width: 33px;
}
</style>
<script>
function start() {
//定時器:每隔10毫秒刷新一次
var kill = window.setInterval("output()", 10);
}
function output() {
//獲取當前日期
var startTime = new Date();
//獲取頁面的日期組合成字符串
var et = $("#ey").val() + "-" + $("#em").val() + "-" + $("#ed").val() + " " + $("#eh").val() + ":" + $("#emin").val() + ":00";
//將字符串類型的日期格式化爲標準日期格式
var endTime = new Date(et);
//將格式化後的時間顯示到頁面
$("#EndTime").val(endTime);
//計算時間差
var nTime = endTime.getTime() - startTime.getTime();
//計算天數
var d = Math.floor(nTime / 86400000);
//計算小時
var h = Math.floor((nTime - (86400000 * d)) / 3600000);
//計算分鐘
var m = Math.floor((nTime - (86400000 * d) - (3600000 * h)) / 60000);
//計算秒數
var s = Math.floor((nTime - (86400000 * d) - (3600000 * h) - (60000 * m)) / 1000);
//計算毫秒數
var t = Math.floor((nTime % 1000)*100);
//將計算後的數據顯示到頁面去
$("#d").val(d);
$("#h").val(h);
$("#m").val(m);
$("#s").val(s);
$("#t").val(t);
}
</script>
<body onload="start()">
<div>
設置結束時間爲:
<input class="ipt four" type="text" name="ey" id="ey" value="2018" /> 年
<input class="ipt two" type="text" name="em" id="em" value="06" /> 月
<input class="ipt two" type="text" name="ed" id="ed" value="19" /> 日
<input class="ipt two" type="text" name="eh" id="eh" value="00" /> :
<input class="ipt two" type="text" name="emin" id="emin" value="00" />
</div>
<div style="margin-top: 50px;">
獲取到結束時間爲:<input style="width: 500px;" type="text" name="EndTime" id="EndTime" value="無數據!">
</div>
<div style="margin-top: 50px;">
倒計時還剩:
<input class="ipt three" type="text" name="d" id="d" value="XXX" />天
<input class="djs" type="text" name="h" id="h" value="XX" />:
<input class="djs" type="text" name="m" id="m" value="XX" />:
<input class="djs" type="text" name="s" id="s" value="XX" />
<input class="djs" type="text" name="t" id="t" value="XX" />
</div>
</body>
</html>
這個可以輸入任意日期和時間來計算距離今天的時間,精確到毫秒,其實也很簡單,懶得解釋,看註釋吧