// 描述
// 倒计时是web开发中常见的组件,请完成second和render两个函数,完成倒计时的显示部分
// 1、second函数的输入为整数,返回{day: Int, hour: Int, min: Int, second: Int}
// 2、render函数的输入为second函数的输出,将数据在页面对应的DOM元素上显示出来,格式如html所示
// 3、如果day为0,隐藏对应的DOM元素,否则显示(请直接使用已经实现的css代码)
// 4、数值不足两位,前面补充0
1.自己的练习
<style>
.hide {
display: none;
}
</style>
<div id="jsCountdown">
<span>01天</span>
<span>02:</span>
<span>03:</span>
<span>04</span>
</div>
function second(second) {
var d = parseInt(second / 3600 / 24)
var hh = parseInt(second / 3600 % 24)
var mm = parseInt(second % 3600 / 60)
var ss = second % 3600 % 60
return { day: d, hour: hh, min: mm, second: ss }
}
// 1. 使用padStart()
function render1(data) {
var d = (data.day + '').padStart(2, '0')
var hh = (data.hour + '').padStart(2, '0')
var mm = (data.min + '').padStart(2, '0')
var ss = (data.second + '').padStart(2, '0')
var div = document.getElementById('jsCountdown')
html = `<span>${d}天</span>
<span>${hh}:</span>
<span>${mm}:</span>
<span>${ss}</span>`
div.innerHTML = html
if (data.day === 0) {
div.children[0].className = 'hide'
}
}
// 2. 自定义函数
function padTwo(dd) {
return dd = dd < 10 ? '0' + dd : dd
}
function render2(data) {
var div = document.getElementById('jsCountdown')
html = `<span>${padTwo(data.day)}天</span>
<span>${padTwo(data.hour)}:</span>
<span>${padTwo(data.min)}:</span>
<span>${padTwo(data.second)}</span>`
div.innerHTML = html
if (data.day === 0) {
div.children[0].className = 'hide'
}
}
2.题解
function second(second) {
let sec = 1
let mintue = 60 * sec
let hour = 60 * mintue
let day = 24 * hour
let rs = {
day: parseInt(second / day),
hour: parseInt(second % day / hour),
min: parseInt(second % hour / mintue),
second: second % mintue,
}
return rs
}
function render(data) {
function len2(d) {
d = '00' + d
return d[d.length-2]+d[d.length-1]
}
let ids = document.querySelector('#jsCountdown')
let html = `
<span class="${data.day ==0? 'hide': ''}">${len2(data.day)}天</span>
<span>${len2(data.hour)}:</span>
<span>${len2(data.min)}:</span>
<span>${len2(data.second)}</span>
`
ids.innerHTML = html
}