下面我将为你提供一个从简单到复杂的、包含多个实例的JavaScript网页设计源代码集合,你可以直接复制这些代码,保存为 .html 文件,然后用浏览器打开即可看到效果。

javascript网页设计源代码
(图片来源网络,侵删)

目录

  1. 基础实例:动态时钟

    一个简单的、实时更新的数字时钟。

  2. 交互实例:待办事项列表

    用户可以添加、删除和标记完成待办事项。

  3. 进阶实例:图片轮播图

    带有自动播放、手动切换和指示器的图片轮播组件。

  4. 综合实例:个人作品集网页

    将上述组件整合到一个更完整的单页面中,展示一个前端开发者的作品集。

    javascript网页设计源代码
    (图片来源网络,侵删)

基础实例:动态时钟

这个例子展示了如何使用 JavaScriptsetInterval 函数来定时更新网页内容。

index.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">JavaScript 动态时钟</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f0f2f5;
        }
        .clock-container {
            background-color: white;
            padding: 40px 60px;
            border-radius: 15px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
            text-align: center;
        }
        #clock {
            font-size: 3.5rem;
            font-weight: bold;
            color: #333;
            letter-spacing: 2px;
        }
    </style>
</head>
<body>
    <div class="clock-container">
        <h1>当前时间</h1>
        <div id="clock">加载中...</div>
    </div>
    <script>
        // 获取显示时间的 <div> 元素
        const clockElement = document.getElementById('clock');
        // 定义一个更新时间的函数
        function updateClock() {
            // 创建一个新的 Date 对象
            const now = new Date();
            // 获取时、分、秒
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');
            // 格式化时间字符串
            const timeString = `${hours}:${minutes}:${seconds}`;
            // 将格式化后的时间更新到页面上
            clockElement.textContent = timeString;
        }
        // 立即执行一次,避免页面加载后等待1秒
        updateClock();
        // 设置一个定时器,每1000毫秒(1秒)调用一次 updateClock 函数
        setInterval(updateClock, 1000);
    </script>
</body>
</html>

代码解释:

  • HTML: 创建了一个包含 id="clock"div 用于显示时间。
  • CSS: 使用 Flexbox 将时钟居中,并添加了美观的样式。
  • JavaScript:
    • document.getElementById('clock'): 获取页面上 idclock 的元素。
    • new Date(): 创建一个包含当前日期和时间的对象。
    • padStart(2, '0'): 确保小时、分钟、秒始终是两位数(7 会变成 07)。
    • setInterval(function, milliseconds): 定期执行一个函数,这里我们用它来每秒更新一次时间。

交互实例:待办事项列表

这个例子展示了如何处理用户输入、修改页面内容以及使用 localStorage 来持久化数据。

todo.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">JavaScript 待办事项列表</title>
    <style>
        body { font-family: 'Helvetica Neue', Arial, sans-serif; background-color: #e9ecef; padding: 20px; }
        .todo-container { max-width: 500px; margin: auto; background: white; padding: 25px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        h1 { text-align: center; color: #333; }
        .input-group { display: flex; margin-bottom: 20px; }
        #todoInput { flex-grow: 1; padding: 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 16px; }
        #addBtn { padding: 10px 15px; border: none; background-color: #007bff; color: white; cursor: pointer; border-radius: 4px; margin-left: 10px; }
        #addBtn:hover { background-color: #0056b3; }
        ul { list-style: none; padding: 0; }
        li { display: flex; justify-content: space-between; align-items: center; padding: 12px; border-bottom: 1px solid #eee; }
        li:last-child { border-bottom: none; }
        .todo-text { flex-grow: 1; }
        .todo-text.completed { text-decoration: line-through; color: #aaa; }
        .delete-btn { background-color: #dc3545; color: white; border: none; padding: 5px 10px; cursor: pointer; border-radius: 4px; }
        .delete-btn:hover { background-color: #c82333; }
    </style>
</head>
<body>
    <div class="todo-container">
        <h1>我的待办事项</h1>
        <div class="input-group">
            <input type="text" id="todoInput" placeholder="输入新的待办事项...">
            <button id="addBtn">添加</button>
        </div>
        <ul id="todoList"></ul>
    </div>
    <script>
        // 获取DOM元素
        const todoInput = document.getElementById('todoInput');
        const addBtn = document.getElementById('addBtn');
        const todoList = document.getElementById('todoList');
        // 从 localStorage 加载待办事项
        let todos = JSON.parse(localStorage.getItem('todos')) || [];
        // 渲染待办列表
        function renderTodos() {
            todoList.innerHTML = ''; // 清空现有列表
            todos.forEach((todo, index) => {
                const li = document.createElement('li');
                li.innerHTML = `
                    <span class="todo-text ${todo.completed ? 'completed' : ''}">${todo.text}</span>
                    <button class="delete-btn" data-index="${index}">删除</button>
                `;
                todoList.appendChild(li);
            });
            // 保存到 localStorage
            localStorage.setItem('todos', JSON.stringify(todos));
        }
        // 添加待办事项
        function addTodo() {
            const text = todoInput.value.trim();
            if (text) {
                todos.push({ text: text, completed: false });
                todoInput.value = ''; // 清空输入框
                renderTodos();
            }
        }
        // 切换完成状态
        function toggleTodo(index) {
            todos[index].completed = !todos[index].completed;
            renderTodos();
        }
        // 删除待办事项
        function deleteTodo(index) {
            todos.splice(index, 1);
            renderTodos();
        }
        // 事件监听
        addBtn.addEventListener('click', addTodo);
        todoInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                addTodo();
            }
        });
        // 使用事件委托处理列表项的点击(删除和切换状态)
        todoList.addEventListener('click', (e) => {
            const index = e.target.getAttribute('data-index');
            if (e.target.classList.contains('delete-btn') && index !== null) {
                deleteTodo(parseInt(index));
            } else if (e.target.classList.contains('todo-text')) {
                const li = e.target.parentElement;
                const index = Array.from(todoList.children).indexOf(li);
                toggleTodo(index);
            }
        });
        // 初始渲染
        renderTodos();
    </script>
</body>
</html>

代码解释:

javascript网页设计源代码
(图片来源网络,侵删)
  • HTML: 包含一个输入框、一个添加按钮和一个用于显示待办事项的列表。
  • CSS: 设计了简洁的列表和按钮样式。
  • JavaScript:
    • localStorage: 浏览器提供的本地存储,关闭页面后数据仍然存在。
    • JSON.parse()JSON.stringify(): 用于在 JavaScript 对象和 JSON 字符串之间转换,以便存储在 localStorage 中。
    • renderTodos(): 核心函数,负责根据 todos 数组重新渲染整个列表。
    • 事件委托: 在 ul 上监听点击事件,而不是为每个 libutton 单独添加监听器,这是一种更高效的做法,特别是当列表项会动态增减时,我们通过 e.target 判断点击的是哪个元素。

进阶实例:图片轮播图

这个例子展示了如何实现一个功能丰富的组件,包括自动播放、暂停、手动切换和指示器。

carousel.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">JavaScript 图片轮播图</title>
    <style>
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body { font-family: Arial, sans-serif; background-color: #f4f4f4; display: flex; justify-content: center; align-items: center; min-height: 100vh; }
        .carousel-container { width: 800px; max-width: 100%; position: relative; overflow: hidden; border-radius: 10px; box-shadow: 0 5px 15px rgba(0,0,0,0.2); }
        .carousel-slide { display: flex; }
        .carousel-slide img { width: 100%; height: auto; display: block; }
        .carousel-btn {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            background-color: rgba(0,0,0,0.5);
            color: white;
            border: none;
            padding: 15px 20px;
            cursor: pointer;
            font-size: 18px;
            transition: background-color 0.3s;
            z-index: 10;
        }
        .carousel-btn:hover { background-color: rgba(0,0,0,0.8); }
        #prevBtn { left: 10px; }
        #nextBtn { right: 10px; }
        .carousel-indicators {
            position: absolute;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            display: flex;
            gap: 10px;
        }
        .indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background-color: rgba(255,255,255,0.5);
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .indicator.active { background-color: white; }
    </style>
</head>
<body>
    <div class="carousel-container">
        <div class="carousel-slide">
            <img src="https://picsum.photos/seed/slide1/800/400.jpg" alt="Slide 1">
            <img src="https://picsum.photos/seed/slide2/800/400.jpg" alt="Slide 2">
            <img src="https://picsum.photos/seed/slide3/800/400.jpg" alt="Slide 3">
            <img src="https://picsum.photos/seed/slide4/800/400.jpg" alt="Slide 4">
        </div>
        <button id="prevBtn">&#10094;</button>
        <button id="nextBtn">&#10095;</button>
        <div class="carousel-indicators"></div>
    </div>
    <script>
        const carouselSlide = document.querySelector('.carousel-slide');
        const images = document.querySelectorAll('.carousel-slide img');
        const prevBtn = document.querySelector('#prevBtn');
        const nextBtn = document.querySelector('#nextBtn');
        const indicatorsContainer = document.querySelector('.carousel-indicators');
        let counter = 0;
        const size = images[0].clientWidth; // 获取第一张图片的宽度
        // 创建指示器
        images.forEach((_, index) => {
            const indicator = document.createElement('div');
            indicator.classList.add('indicator');
            if (index === 0) indicator.classList.add('active');
            indicator.addEventListener('click', () => {
                counter = index;
                updateCarousel();
            });
            indicatorsContainer.appendChild(indicator);
        });
        const indicators = document.querySelectorAll('.indicator');
        // 克隆第一张图片放到最后,实现无缝循环
        const firstImgClone = images[0].cloneNode(true);
        carouselSlide.appendChild(firstImgClone);
        // 初始位置
        carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
        function updateCarousel() {
            carouselSlide.style.transition = 'transform 0.5s ease-in-out';
            carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
            // 更新指示器
            indicators.forEach(ind => ind.classList.remove('active'));
            indicators[counter % (images.length)].classList.add('active');
            // 当到达克隆的图片时,瞬间跳回第一张
            if (counter >= images.length) {
                setTimeout(() => {
                    carouselSlide.style.transition = 'none';
                    counter = 0;
                    carouselSlide.style.transform = 'translateX(' + (-size * counter) + 'px)';
                }, 500);
            }
        }
        // 下一张
        nextBtn.addEventListener('click', () => {
            if (counter >= images.length) return; // 防止在克隆图片上点击
            counter++;
            updateCarousel();
        });
        // 上一张
        prevBtn.addEventListener('click', () => {
            if (counter <= 0) return; // 防止在第一张图片上点击
            counter--;
            updateCarousel();
        });
        // 自动播放
        let slideInterval = setInterval(() => {
            nextBtn.click();
        }, 3000);
        // 鼠标悬停时暂停自动播放
        carouselSlide.addEventListener('mouseenter', () => {
            clearInterval(slideInterval);
        });
        // 鼠标离开时恢复自动播放
        carouselSlide.addEventListener('mouseleave', () => {
            slideInterval = setInterval(() => {
                nextBtn.click();
            }, 3000);
        });
    </script>
</body>
</html>

代码解释:

  • HTML: 轮播图容器、图片列表、左右切换按钮和底部指示器。
  • CSS: 使用 overflow: hiddenposition: relative 创建视口,通过 transform: translateX() 来移动图片列表,实现平滑的切换效果。
  • JavaScript:
    • 无缝循环: 通过克隆第一张图片并放置到列表末尾,当用户滑动到最后一张(克隆图)时,利用 setTimeout 在动画结束后瞬间跳回第一张,同时重置 transform,形成无缝循环。
    • 自动播放: 使用 setInterval 定时触发“下一张”的点击事件。
    • 交互增强: 鼠标悬停在轮播图上时,clearInterval 清除定时器,暂停自动播放;鼠标离开时,重新设置定时器,恢复播放。

综合实例:个人作品集网页

这个例子将上述三个组件整合在一起,展示了一个更完整的网页结构。

portfolio.html

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">张三 - 前端开发工程师</title>
    <style>
        /* 全局样式和重置 */
        * { box-sizing: border-box; margin: 0; padding: 0; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            line-height: 1.6;
            color: #333;
            background-color: #f9f9f9;
        }
        .container {
            max-width: 1100px;
            margin: 0 auto;
            padding: 0 20px;
        }
        header {
            background: #fff;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            padding: 1rem 0;
            position: sticky;
            top: 0;
            z-index: 100;
        }
        nav {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .logo { font-size: 1.5rem; font-weight: bold; }
        nav ul {
            display: flex;
            list-style: none;
        }
        nav ul li { margin-left: 20px; }
        nav ul li a {
            text-decoration: none;
            color: #333;
            font-weight: 500;
            transition: color 0.3s;
        }
        nav ul li a:hover { color: #007bff; }
        /* 主要内容区域样式 */
        section {
            padding: 60px 0;
        }
        h1, h2 { text-align: center; margin-bottom: 30px; }
        h1 { font-size: 2.5rem; color: #2c3e50; }
        h2 { font-size: 2rem; color: #34495e; }
        /* 英雄区域 */
        #hero {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            color: white;
            text-align: center;
            padding: 100px 0;
        }
        #hero p { font-size: 1.2rem; margin-bottom: 20px; }
        /* 时钟区域 */
        #clock-section { text-align: center; }
        .clock-container { /* 使用时钟实例的样式 */ }
        /* 待办事项区域 */
        #todo-section { background: #fff; }
        .todo-container { /* 使用待办事项实例的样式 */ }
        /* 轮播图区域 */
        #carousel-section { background: #fff; }
        .carousel-container { /* 使用轮播图实例的样式 */ }
        /* 页脚 */
        footer {
            background: #333;
            color: #fff;
            text-align: center;
            padding: 20px 0;
        }
    </style>
</head>
<body>
    <header>
        <nav class="container">
            <div class="logo">张三的作品集</div>
            <ul>
                <li><a href="#hero">首页</a></li>
                <li><a href="#clock-section">时钟</a></li>
                <li><a href="#todo-section">待办事项</a></li>
                <li><a href="#carousel-section">项目展示</a></li>
            </ul>
        </nav>
    </header>
    <main>
        <section id="hero">
            <div class="container">
                <h1>你好,我是张三</h1>
                <p>一名充满激情的前端开发工程师</p>
                <p>专注于创造优雅、高效的用户体验</p>
            </div>
        </section>
        <section id="clock-section">
            <div class="container">
                <h2>当前时间</h2>
                <!-- 时钟组件的HTML -->
                <div class="clock-container">
                    <div id="clock">加载中...</div>
                </div>
            </div>
        </section>
        <section id="todo-section">
            <div class="container">
                <h2>我的任务列表</h2>
                <!-- 待办事项组件的HTML -->
                <div class="todo-container">
                    <div class="input-group">
                        <input type="text" id="todoInput" placeholder="输入新的待办事项...">
                        <button id="addBtn">添加</button>
                    </div>
                    <ul id="todoList"></ul>
                </div>
            </div>
        </section>
        <section id="carousel-section">
            <div class="container">
                <h2>项目展示</h2>
                <!-- 轮播图组件的HTML -->
                <div class="carousel-container">
                    <div class="carousel-slide">
                        <img src="https://picsum.photos/seed/proj1/800/400.jpg" alt="项目1 - 电商网站">
                        <img src="https://picsum.photos/seed/proj2/800/400.jpg" alt="项目2 - 数据可视化">
                        <img src="https://picsum.photos/seed/proj3/800/400.jpg" alt="项目3 - 移动应用">
                        <img src="https://picsum.photos/seed/proj4/800/400.jpg" alt="项目4 - 企业官网">
                    </div>
                    <button id="prevBtn">&#10094;</button>
                    <button id="nextBtn">&#10095;</button>
                    <div class="carousel-indicators"></div>
                </div>
            </div>
        </section>
    </main>
    <footer>
        <div class="container">
            <p>&copy; 2025 张三. All rights reserved.</p>
        </div>
    </footer>
    <!-- 将上面三个实例的JavaScript代码合并到这里 -->
    <script>
        // ==================== 时钟脚本 ====================
        const clockElement = document.getElementById('clock');
        function updateClock() {
            const now = new Date();
            const hours = String(now.getHours()).padStart(2, '0');
            const minutes = String(now.getMinutes()).padStart(2, '0');
            const seconds = String(now.getSeconds()).padStart(2, '0');
            clockElement.textContent = `${hours}:${minutes}:${seconds}`;
        }
        updateClock();
        setInterval(updateClock, 1000);
        // ==================== 待办事项脚本 ====================
        const todoInput = document.getElementById('todoInput');
        const addBtn = document.getElementById('addBtn');
        const todoList = document.getElementById('todoList');
        let todos = JSON.parse(localStorage.getItem('todos')) || [];
        function renderTodos() {
            todoList.innerHTML = '';
            todos.forEach((todo, index) => {
                const li = document.createElement('li');
                li.innerHTML = `
                    <span class="todo-text ${todo.completed ? 'completed' : ''}">${todo.text}</span>
                    <button class="delete-btn" data-index="${index}">删除</button>
                `;
                todoList.appendChild(li);
            });
            localStorage.setItem('todos', JSON.stringify(todos));
        }
        function addTodo() {
            const text = todoInput.value.trim();
            if (text) {
                todos.push({ text, completed: false });
                todoInput.value = '';
                renderTodos();
            }
        }
        function deleteTodo(index) {
            todos.splice(index, 1);
            renderTodos();
        }
        function toggleTodo(index) {
            todos[index].completed = !todos[index].completed;
            renderTodos();
        }
        addBtn.addEventListener('click', addTodo);
        todoInput.addEventListener('keypress', (e) => e.key === 'Enter' && addTodo());
        todoList.addEventListener('click', (e) => {
            const index = e.target.getAttribute('data-index');
            if (e.target.classList.contains('delete-btn') && index !== null) {
                deleteTodo(parseInt(index));
            } else if (e.target.classList.contains('todo-text')) {
                const li = e.target.parentElement;
                const index = Array.from(todoList.children).indexOf(li);
                toggleTodo(index);
            }
        });
        renderTodos();
        // ==================== 轮播图脚本 ====================
        const carouselSlide = document.querySelector('.carousel-slide');
        const images = document.querySelectorAll('.carousel-slide img');
        const prevBtn = document.querySelector('#prevBtn');
        const nextBtn = document.querySelector('#nextBtn');
        const indicatorsContainer = document.querySelector('.carousel-indicators');
        let slideCounter = 0;
        const slideSize = images[0].clientWidth;
        images.forEach((_, index) => {
            const indicator = document.createElement('div');
            indicator.classList.add('indicator');
            if (index === 0) indicator.classList.add('active');
            indicator.addEventListener('click', () => {
                slideCounter = index;
                updateCarousel();
            });
            indicatorsContainer.appendChild(indicator);
        });
        const indicators = document.querySelectorAll('.indicator');
        const firstImgClone = images[0].cloneNode(true);
        carouselSlide.appendChild(firstImgClone);
        carouselSlide.style.transform = 'translateX(' + (-slideSize * slideCounter) + 'px)';
        function updateCarousel() {
            carouselSlide.style.transition = 'transform 0.5s ease-in-out';
            carouselSlide.style.transform = 'translateX(' + (-slideSize * slideCounter) + 'px)';
            indicators.forEach(ind => ind.classList.remove('active'));
            indicators[slideCounter % images.length].classList.add('active');
            if (slideCounter >= images.length) {
                setTimeout(() => {
                    carouselSlide.style.transition = 'none';
                    slideCounter = 0;
                    carouselSlide.style.transform = 'translateX(' + (-slideSize * slideCounter) + 'px)';
                }, 500);
            }
        }
        nextBtn.addEventListener('click', () => {
            if (slideCounter >= images.length) return;
            slideCounter++;
            updateCarousel();
        });
        prevBtn.addEventListener('click', () => {
            if (slideCounter <= 0) return;
            slideCounter--;
            updateCarousel();
        });
        let slideInterval = setInterval(() => {
            nextBtn.click();
        }, 3000);
        carouselSlide.addEventListener('mouseenter', () => clearInterval(slideInterval));
        carouselSlide.addEventListener('mouseleave', () => {
            slideInterval = setInterval(() => {
                nextBtn.click();
            }, 3000);
        });
    </script>
</body>
</html>

这个综合实例展示了如何将独立的组件组合成一个功能齐全的单页面应用,你可以通过修改CSS来调整布局和样式,通过修改JavaScript来增强功能,这就是前端开发的基本流程,希望这些源代码能帮助你更好地理解JavaScript在网页设计中的应用!