🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
### 数码时钟 - 效果思路 - 获取系统时间 - `new Date` 对象 - `getHours / getMinutes / getSeconds` - 显示系统时间 - 字符串连接 - 空位补零 - 设置图片路径 - `str[i]`:取出字符串中的第 i 个值,不兼容 ie7 - `charAt(i)` 方法 :取出字符串中的第 i 个值,兼容各种浏览器 - 设置路径:`"url('img/0.png')"` - JavaScript 中的 String 方法 - `obj.charAt(index)` - 返回index位置的字符 - `obj.charCodeAt()` - 返回index位置的字符编码 - `obj.indexOf("str")` - 顺序搜索str,返回其位置,未找到返回-1 - `obj.lastIndexOf("str")` - 倒序搜索str,返回其位置,未找到返回-1 - `slice(start,end)`:同数组 - `substring(start,end)`:同上,区别在于参数为负数时自动转换为0,并且较小的数为起始位 - `substr(start,len)`:同上,len 表示截取的长度 - 代码: ```HTML <!DOCTYPE html> <html> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>数码时钟</title> <style> body{ margin: 0; padding: 0; background-color: rgb(49, 49, 49); } li { list-style: none; float: left; width: 100px; height: 149px; } span { float: left; font-size: 100px; color: rgb(255, 255, 255); } </style> <script> window.onload = function () { // 封装 getElementsByTagName function gets(tagName) { return document.getElementsByTagName(tagName) } // 数码时钟 // 数字时钟图片设置函数 const oLi = gets('li'); function clock() { const date = new Date(); const str = addZero(date.getHours()) + addZero(date.getMinutes()) + addZero(date.getSeconds()); let i = 0; for (i = 0; i < oLi.length; i++) { oLi[i].style.backgroundImage = "url('img/"+ str.charAt(i) +".png')"; } } // 补零 function addZero(num) { if (num < 10) { num = '0' + num; } else { num = '' + num; } return num; } // 先执行一遍,就不会出现一秒的空白,定时器要 window.onload 完一秒后才执行 clock(); // 定时器 每秒刷新一次 setInterval(clock, 1000); } </script> <body> <ul> <li></li> <li></li> <span>:</span> <li></li> <li></li> <span>:</span> <li></li> <li></li> </ul> </body> </html> ```