js动态数字时钟
主要用到知识点:
- 主要是通过数组的一些方法,如:Array.from() Array.reduce() Array.find()
- 时间的处理和渲染
- js用到面向对象的写法
实现的功能
- 炫酷的数字时间效果
- 直接看效果
html:
<div class="wraper">
<div class="column">
<div class="item">0</div>
<div class="item">1</div>
<div class="item">2</div>
</div>
<div class="column ten"></div>
<div class="colon">:</div>
<div class="column six"></div>
<div class="column ten"></div>
<div class="colon">:</div>
<div class="column six"></div>
<div class="column ten"></div>
</div>
css:
* {
margin: 0;
padding: 0;
}
html,
body {
100%;
height: 100%;
background-color: #0e141b;
}
.wraper {
100%;
height: 100%;
text-align: center;
overflow: hidden;
}
.column,
.colon {
display: inline-block;
vertical-align: top;
color: #fff;
font-size: 86px;
line-height: 86px;
font-weight: 300;
transform: translateY(50vh);
margin-top: -43px;
transition: all 0.3s;
}
.visible {
opacity: 1;
box-shadow: 0px 0px 20px #fff;
border-radius: 5px;
}
.near1 {
opacity: 0.7;
}
.near2 {
opacity: 0.6;
}
.near3 {
opacity: 0.4;
}
.far1 {
opacity: 0.3;
}
.far2 {
opacity: 0.2;
}
.far3 {
opacity: 0.1;
}
.none {
opacity: 0.05;
}
js:
function Time(bom,use24){
this.Bom = Array.from(bom);
this.format = use24;
this.classList = ['visible', 'near1', 'near2','near3', 'far1', 'far2', 'far3'];
this.creatDom();
this.setTime();
}
//生成dom元素
Time.prototype.creatDom=function(){
for(let i=0;i<6;i++){
let odiv = "<div class='item'>"+i+"</div>";
$('.six').append(odiv);
}
for(let i=0;i<10;i++){
let idiv = "<div class='item'>" + i + "</div>";
$('.ten').append(idiv);
}
}
//设置当前时间到页面
Time.prototype.setTime = function(){
let self =this;
setInterval(function(){
let presentTime = self.getTime();
self.Bom.forEach((ele,index)=>{
var n = +presentTime[index];
var offset = n * 86;
$(ele).css({
marginTop:-43 - offset +'px'
})
Array.from(ele.children).forEach(function (ele1,index1){
$(ele1).attr('class', self.getClassName(n,index1));
})
})
},500)
}
Time.prototype.getClassName = function(n,i){
let className = this.classList.find(function(item,index){
return i - index === n || i + index === n;
})
// console.log(className)
return className || 'none';
}
//获取当前时间并处理
Time.prototype.getTime=function(){
let Data = new Date();
let timeArr =[];
let timeStr = '';
timeArr.push(this.format ? Data.getHours() : Data.getHours() % 12 || 12, Data.getMinutes(),Data.getSeconds());
timeStr = timeArr.reduce(function(p,n){
return p + ('0' + n).slice(-2);
},'');
return timeStr;
}
new Time($('.column'),true);
参考自:腾讯课堂渡一教育