本文实例为大家分享了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>