demo : http://dsj-666.gitee.io/clock
源码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="index.css">
<script src="jquery-3.4.1.js"></script>
<script src="index.js"></script>
</head>
<body>
<div class="wrapper">
<div class="column">
<div>0</div>
<div>1</div>
<div>2</div>
</div>
<div class="column ten"></div>
<div class="coln">:</div>
<div class="column six"></div>
<div class="column ten"></div>
<div class="coln">:</div>
<div class="column six"></div>
<div class="column ten"></div>
</div>
</body>
</html>
* {
padding: 0;
margin: 0;
}
body {
width: 100%;
height: 100%;
background-color: #1c2028;
overflow: hidden;
}
.wrapper {
width: 100%;
text-align: center;
}
.wrapper [class*=col] {
display: inline-block;
margin-left: 20px;
vertical-align: top;
color: white;
font-size: 86px;
line-height: 86px;
font-weight: 300;
transition: all 300ms ease;
}
.coln {
transform: translateY(calc(50vh + 43px));
}
window.onload = function() {
var obj = {
ten: $("[class *=ten]"),
six: $("[class *=six]"),
colum: $("[class*=column]"),
use24: true,
init: function() {
this.createDom(6);
this.createDom(10);
},
createDom: function(n) {
var div = '';
for (var i = 0; i < n; i++) {
div += '<div>' + i + '</div>';
}
if (n == 6) {
this.six.append(div);
} else {
this.ten.append(div);
}
},
Index: function(jq, use24) {
this.colum = Array.from(jq);
this.use24 = use24;
this.start();
},
start: function() {
setInterval(() => {
var c = this.getClock();
console.log(this.colum);
this.colum.forEach(function(ele, index) {
// console.log(c[index]);
var n = c[index];
var offset = 430 - n * 86 + 'px';
$(ele).css({
'transform': 'translateY(' + offset + ')',
})
Array.from(ele.children).forEach(function(ele2) {
var op = 1 - Math.abs(n - parseInt($(ele2).html())) / 8;
$(ele2).css({
'opacity': op
})
})
})
}, 500)
},
getClock: function() {
var d = new Date();
return [this.use24 ? d.getHours() : d.getHours() % 12 || 12, d.getMinutes(), d.getSeconds()].reduce(function(pre, now) {
//将22:10:09 转变为'221009'
return pre + (now + '').padStart(2, '0');
// return pre + ('0' + now).slice(-2);
}, '')
},
}
obj.init();
obj.Index(obj.colum, false);
}
注意点:
- calc()方法 用来计算长度值,最后都转换成了px 注意运算符左右拿空格隔开
主要思路:
- 通过reduce()方法来将获取到的时间转换为字符串连接,不足位补零
- 利用计时器不断地 获取时间
- jQuery对象转为数组并遍历,根据返回字符的数字来设置相应元素的偏移量就实现
- 其他数字相差多少来设置透明度