利用HTML+CSS+JS打造炫酷时钟网页的完整指南

引言

在现代Web开发中,制作一个引人注目的时钟网页是一种常见而令人愉悦的体验。本文将介绍如何使用HTML、CSS和JavaScript来创建一个炫酷的时钟网页,通过这个项目,你将学到如何结合这三种前端技术,制作一个动态且美观的时钟效果。

步骤一:创建HTML结构

首先,创建HTML文件,定义时钟网页的基本结构:



	
		
		
		
	
	
		
0
1
2
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
0
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
0
1
2
3
4
5
6
7
8
9

步骤二:美化时钟样式(CSS)

创建一个名为 styles.css 的CSS文件,用于美化时钟的外观:

* {
    box-sizing: border-box;
    padding: 0;
    margin: 0;
}

html {
    place-items: center;
}

body {
    font-family: monospace;
    font-size: 2rem;
    min-height: 100vh;
    display: grid;
    overflow-y: hidden;
    place-items: center;
    background: linear-gradient(-45deg, #c4d2ef, #dfe6f6);
}

.hr,
.min,
.sec {
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-gap: 3rem;
    grid-row: 1/2;
    align-items: start;
}

.number {
    padding: 0.5em;
    width: 4rem;
    height: 4rem;
    display: grid;
    place-items: center;
    color: #f9fbfd;
    transition: all 500ms 100ms ease;
    border-radius: 50%;
}

.number.pop {
    color: #3e6ccb;
    font-weight: bold;
    transform: scale(1.3);
    background-color: #dfe6f6;
    box-shadow: -10px -10px 20px -5px #f9fbfd, 10px 10px 20px #a9bee8;
}

.strip {
    transition: transform 500ms ease-in-out;
    border-radius: 8px;
    background-color: #dfe6f6;
    box-shadow: -10px -10px 20px -5px #f9fbfd, 10px 10px 20px #a9bee8;
}

.clock {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-gap: 5rem;
    height: 4rem;
    position: relative;
    padding: 0 4rem;
}

步骤三:实现时钟逻辑(JavaScript)

在 index.js 文件中,编写JavaScript代码来获取当前时间,并根据时间更新时钟的指针位置:

const strips = [...document.querySelectorAll(".strip")];
const numberSize = "4"; 

var lastTime = new Array(-1, -1, -1)


function highlight(strip, d) {
    strips[strip]
        .querySelector(`.number:nth-of-type(${d + 1})`)
        .classList.add("pop");

    setTimeout(() => {
        strips[strip]
            .querySelector(`.number:nth-of-type(${d + 1})`)
            .classList.remove("pop");
    }, 950); 
}

function stripSlider(strip, id, number) {
    let d1 = Math.floor(number / 10);
    let d2 = number % 10;

    if (lastTime[id] == -1 || lastTime[id] != number) {
        strips[strip].style.transform = `translateY(${d1 * -numberSize}rem)`;
        strips[strip + 1].style.transform = `translateY(${d2 * -numberSize}rem)`;

        lastTime[id] = number;
    }

    highlight(strip, d1);
    highlight(strip + 1, d2);
}

function updateClock() {
    
    const time = new Date();

   
    const hours = time.getHours();
    const mins = time.getMinutes();
    const secs = time.getSeconds();

   
    stripSlider(0, 0, hours);
    stripSlider(2, 1, mins);
    stripSlider(4, 2, secs);
}


setInterval(updateClock, 1000);

updateClock();

结语

通过本文的指南,你已经学会如何使用HTML、CSS和JavaScript创建一个炫酷的时钟网页。这个项目结合了这三种前端技术,展示了它们的协同作用。通过这个实践,你不仅提升了前端技术的应用能力,还掌握了制作动态效果的基本原理。希望这个时钟网页项目能够成为你继续学习前端开发的良好起点。

你可能感兴趣的:(html,css,javascript)