用JavaScript實現(xiàn)簡單網(wǎng)頁時鐘
利用JavaScript實現(xiàn)網(wǎng)頁時鐘,效果如下圖所示:
首先在body中完成表盤、指針的資源載入:
<div><img src='http://www.aoyou183.cn/image/clockface.jpg' alt=''></div><hr ><hr id='min'><hr id='second'>
設置CSS樣式:
<style>body{ margin: 0;}div{ margin: 0 auto; width: 600px; height: 600px;}#hour{ background-color: black; width: 130px; height: 10px; position: fixed; top: 295px; left: 50%; margin-left: -65px;}#min{ background-color: red; width: 200px; height: 8px; position: fixed; top: 296px; left: 50%; margin-left: -100px;}#second{ background-color: yellow; width: 270px; height: 5px; position: fixed; top: 297.5px; left: 50%; margin-left: -135px;}</style>
最后是JS代碼部分,使用循環(huán)定時器setInterval()每秒調用一次主函數(shù),主函數(shù)內使用new Date()創(chuàng)建時間對象,分別使用 .getHours();.getMinutes();.getSeconds()獲得當前的時分秒,然后利用CSS自帶動畫-旋轉改變指針的角度:
setInterval(watch,1000);var anjleSeconds=0,anjleMin=0,anjleHours=0;function watch() {var Time= new Date();anjleSeconds=Time.getSeconds()/60*360+90;anjleMin=Time.getMinutes()/60*360+90;anjleHours=nowHours/12*360+90;document.getElementById('second').style.transform='rotate('+anjleSeconds+'deg)';document.getElementById('min').style.transform='rotate('+anjleMin+'deg)';document.getElementById('hour').style.transform='rotate('+anjleHours+'deg)'; }
目前存在的問題是,時分秒指針由于使用的是hr標簽表示,所以存在兩端一樣長的問題。
完整代碼如下:
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <title>Title</title> <style>body{ margin: 0;}div{ margin: 0 auto; width: 600px; height: 600px;}#hour{ background-color: black; width: 130px; height: 10px; position: fixed; top: 295px; left: 50%; margin-left: -65px;}#min{ background-color: red; width: 200px; height: 8px; position: fixed; top: 296px; left: 50%; margin-left: -100px;}#second{ background-color: yellow; width: 270px; height: 5px; position: fixed; top: 297.5px; left: 50%; margin-left: -135px;} </style></head><body><div><img src='http://www.aoyou183.cn/image/clockface.jpg' alt=''></div><hr ><hr id='min'><hr id='second'><script> setInterval(watch,1000); var anjleSeconds=0,anjleMin=0,anjleHours=0; function watch() {var Time= new Date();anjleSeconds=Time.getSeconds()/60*360+90;anjleMin=Time.getMinutes()/60*360+90;anjleHours=Time.getHours()/12*360+90;document.getElementById('second').style.transform='rotate('+anjleSeconds+'deg)';document.getElementById('min').style.transform='rotate('+anjleMin+'deg)';document.getElementById('hour').style.transform='rotate('+anjleHours+'deg)'; }</script></body></html>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關文章:
1. React+umi+typeScript創(chuàng)建項目的過程2. .Net core 的熱插拔機制的深入探索及卸載問題求救指南3. ASP調用WebService轉化成JSON數(shù)據(jù),附json.min.asp4. SharePoint Server 2019新特性介紹5. 三個不常見的 HTML5 實用新特性簡介6. 解決ASP中http狀態(tài)跳轉返回錯誤頁的問題7. ASP中常用的22個FSO文件操作函數(shù)整理8. 無線標記語言(WML)基礎之WMLScript 基礎第1/2頁9. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過程解析10. ASP編碼必備的8條原則
