以無聊的名義...這個頁面應該更新javascript沒有jquery的時間跨度。
<!doctype html>
<html>
<body onload="init()">
<script type="text/javascript">
function init() {
updateTimespan();
setInterval(updateTimespan, 3000);
}
function updateTimespan() {
var birth = new Date(1987, 3, 20); // april 20th
var now = new Date();
var timespan = getTimespan(birth, now);
var content = '' + timespan.years + ' years, ' +
timespan.months + ' months, ' +
timespan.days + ' days, ' +
timespan.hours + ' hours, ' +
timespan.minutes + ' minutes, ' +
timespan.seconds + ' seconds.';
var p = document.getElementById('pTimespan');
p.innerHTML = content;
}
function getTimespan(start, end) {
var seconds = end.getSeconds() - start.getSeconds();
var minutes = end.getMinutes() - start.getMinutes();
var hours = end.getHours() - start.getHours();
var days = end.getDate() - start.getDate();
var months = end.getMonth() - start.getMonth();
var years = end.getFullYear() - start.getFullYear();
if (seconds < 0) {
minutes -= 1;
seconds += 60;
}
if (minutes < 0) {
hours -= 1;
minutes += 60;
}
if (hours < 0) {
days -= 1;
hours += 24;
}
if (days < 0) {
months -= 1;
var lastMonthNumber = end.getMonth() - 1;
if (lastMonthNumber < 0) { lastMonthNumber += 12; } // will never be Feb.
var daysInLastMonth = new Date(end.getFullYear(), lastMonthNumber, 0).getDate();
days += daysInLastMonth;
}
if (months < 0) {
years -= 1;
months += 12;
}
return {
years: years,
months: months,
days: days,
hours: hours,
minutes: minutes,
seconds: seconds
};
}
</script>
<p>
Time since my birth</p>
<p id="pTimespan">
Will be updated</p>
</body>
</html>
來源
2012-06-27 17:25:01
Jon
在movies.io的情況下,他們正在使用Ajax調用更新計數器。 – Jon
可能重複的[如何計算日期差異在JavaScript](http://stackoverflow.com/questions/7763327/how-to-calculate-date-difference-in-javascript) –
你推薦什麼答案?有點難以引起不是很多的投票和不被接受的答案。 – user1431627