在HTML中,我們可以輕松地使用JavaScript代碼來實(shí)現(xiàn)點(diǎn)擊按鈕顯示當(dāng)前時(shí)間時(shí)分秒的效果,代碼如下:
function showTime() { var today = new Date(); var h = today.getHours(); var m = today.getMinutes(); var s = today.getSeconds(); //添加前導(dǎo)0 h = checkTime(h); m = checkTime(m); s = checkTime(s); document.getElementById('time').innerHTML = h + ":" + m + ":" + s; } function checkTime(i) { if (i< 10) { i = "0" + i; //在數(shù)字前添加一個(gè)“0” } return i; }
以上是JavaScript代碼,下面我們來看一下如何在HTML中應(yīng)用它。首先,我們需要為用戶定義一個(gè)按鈕,當(dāng)用戶點(diǎn)擊該按鈕時(shí),就會(huì)觸發(fā)JavaScript代碼來顯示當(dāng)前時(shí)間。代碼如下:
<button onclick="showTime()">顯示時(shí)間</button>
最后,我們需要在HTML中定義一個(gè)用于包含時(shí)間的div元素(或其他元素),這里我們假設(shè)該元素的id為time。代碼如下:
<div id="time"></div>
整個(gè)HTML代碼如下:
<html> <head> <title>顯示當(dāng)前時(shí)間</title> <script> function showTime() { var today = new Date(); var h = today.getHours(); var m = today.getMinutes(); var s = today.getSeconds(); //添加前導(dǎo)0 h = checkTime(h); m = checkTime(m); s = checkTime(s); document.getElementById('time').innerHTML = h + ":" + m + ":" + s; } function checkTime(i) { if (i < 10) { i = "0" + i; //在數(shù)字前添加一個(gè)“0” } return i; } </script> </head> <body> <button onclick="showTime()">顯示時(shí)間</button> <div id="time"></div> </body> </html>
以上就是使用HTML和JavaScript實(shí)現(xiàn)點(diǎn)擊按鈕顯示當(dāng)前時(shí)間時(shí)分秒的方法。妥妥的!