JavaScript 基础
深入数据和类型
函数进阶
运算符
浏览器存储
Document
Web API
事件
工具与规范
实例
练习
$$demo <div class="container"> <div class="hours"> <span class="label"></span> <span class="value"></span> </div> <div class="minutes"></div> <div class="seconds"></div> </div>
<script>
function fillZero(n) {
return n < 10 ? 0${n}
: n
}
function formatHour(hour) {
hour = hour % 12
return hour == 0 ? 12 : hour
}
function fresh() {
let now = new Date()
document.querySelector(".label").innerText =
now.getHours() < 12 ? "AM" : "PM"
document.querySelector(".hours .value").innerText = formatHour(
now.getHours()
)
document.querySelector(".minutes").innerText = fillZero(
now.getMinutes()
)
document.querySelector(".seconds").innerText = fillZero(
now.getSeconds()
)
}
fresh() // 避免开始 1 秒内为 0
setInterval(fresh, 1000)
</script>
<style> html { background-color: black; min-height: 400px; } .container { position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
width: min-content;
height: min-content;
display: flex;
align-items: flex-end;
font-size: 20vmin;
gap: 0.2em;
}
.hours,
.minutes,
.seconds {
background-color: #0f0f0f;
color: #b7b7b7;
}
.hours,
.minutes,
.seconds {
border-radius: 0.1em;
width: 1.4em;
text-align: center;
}
.seconds {
font-size: 10vmin;
}
.hours {
position: relative;
}
.hours .label {
position: absolute;
left: 1.5em;
top: 1.5em;
font-size: 2vmin;
}
</style>
$$