我有一個倒計時鐘,我用HTML和Javascript做的。目前,當它加載時,由於具有動態寬度,文本將在屏幕上晃動。這是因爲我試圖強制它顯示在頁面的中心。我正在尋找一種強制值始終爲兩位數的方法。有沒有一種方法(通過類似if語句的東西),我可以在所有小於10的值之前預先設置一個0?我嘗試着自己實施一些東西,但沒有奏效,所以我評論了它。下面是代碼:在小於10的數字上加一個「0」?
<!DOCTYPE html>
<html>
<style>
body {
background: #ffffff url("http://i.imgur.com/MelSn4S.png") no-repeat left top;
}
@font-face {
font-family: sensation;
src: url(arial);
}
div {
color: white;
font-family: arial;
font-size: 60px;
position: absolute;
top: 50%;
margin-left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%)
}
</style>
<head>
<script type="text/javascript">
var tenYearsInSeconds = 315360000;
var yearInSeconds = 31536000;
var monthInSeconds = 2592000;
var dayInSeconds = 84600;
var hourInSeconds = 3600;
var minuteInSeconds = 60;
var timer = window.setInterval(function() {countdown()}, 10);
var runonce = true;
function countdown() {
var temp = tenYearsInSeconds;
var years = Math.floor(temp/yearInSeconds);
temp = temp % yearInSeconds;
var months = Math.floor(temp/monthInSeconds);
temp = temp % monthInSeconds;
var days = Math.floor(temp/dayInSeconds);
temp = temp % dayInSeconds;
var hours = Math.floor(temp/hourInSeconds);
temp = temp % hourInSeconds;
var minutes = Math.floor(temp/minuteInSeconds);
document.getElementById('time').innerHTML =
"Years: " + years +
" Months: " + months +
" Days: " + days +
" Hours: " + hours +
" Minutes: " + minutes;
tenYearsInSeconds = tenYearsInSeconds - 30000;
if (tenYearsInSeconds <=0 && runonce) {
tenYearsInSeconds = 0;
runonce = false;
countdown();
clearInterval(timer);
}
//if (years < 10) {
//years = "0" + years;
//}
}
</script>
</head>
<body>
<script type="text/javascript">
countdown();
</script>
<div id="time"></div>
</body>
</html>
http://jsfiddle.net/5yrn8L0w/,看到了'格式()'函數。 – jmar777
確保在顯示值之前進行格式設置(在document.getElementById('time')。innerHTML = ...'語句)中完成。根據您註釋掉的代碼的位置,看起來您之後正在執行此操作。 –
謝謝各位的意見。這很有幫助。 –