js實現電子時鐘效果
本文實例為大傢分享瞭js實現電子時鐘效果的具體代碼,供大傢參考,具體內容如下
代碼區域
代碼如下(示例):
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> #watch{ margin-top: 200px; font-size:100px; text-align: center; } </style> </head> <body> <div id = "watch"></div> <script> //獲取id是 watch的元素 var watch = document.getElementById('watch'); //調用 獲取日期時間 getDateTime(); //開啟定時器 setInterval (getDateTime,1000); //定義定時器的回調函數,獲取當前日期時間 function getDateTime(){ //創建時間,日期,對象 var date = new Date(); //獲取年月日時分秒 var y = date.getFullYear(); var m = date.getMonth()+1; var d = date.getDate(); var h = date.getHours(); var i = date.getMinutes(); var s = date.getSeconds(); //如果個位前面補充零 m = m < 10 ? '0' + m : m; d = d < 10 ? '0' + d : d; h = h < 10 ? '0' + h : h; i = i < 10 ? '0' + i : i; s = s < 10 ? '0' + s : s; var dateTimeStr = y + '-'+ m + '-'+ d + ' '+ h + ':' + i + ':' + s ; //把字符串顯示在元素中 watch.innerHTML = dateTimeStr; } </script> </body> </html>
之前小編收藏瞭一段電子時鐘的實現代碼,分享給大傢,也謝謝原作者的分享:
<!DOCTYPE html> <html> <head> <style type="text/css" media="screen"> body { background: black; } #txt { position: absolute; top: 50%; left: 50%; transform: translateX(-50%) translateY(-50%);/*使時鐘居中顯示*/ color: greenyellow; font-size: 60px; font-family: sans-serif; letter-spacing: 7px; /*creating a gradient to be used as background, and then clipping mask with text that shows background only where text is present.*/ background-image: linear-gradient(to bottom right, red, yellow, green); color:transparent; -webkit-background-clip: text; border: 5px solid silver; } </style> <script> function startTime() { var today = new Date(); var h = today.getHours(); var m = today.getMinutes(); var s = today.getSeconds(); m = showInTwoDigits(m); s = showInTwoDigits(s); document.getElementById('txt').innerHTML = h + ":" + m + ":" + s; setTimeout(startTime, 1000);//設定刷新頻率為1000毫秒 } function showInTwoDigits(i) { if (i < 10) {i = "0" + i}; // 10以下的數字前加0 return i; } </script> </head> <body onload="startTime()"> <div id="txt"></div> </body> </html>
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。