如何编写自动切换壁纸并日期

wen 实用脚本 1

这是您需要的自动切换壁纸并显示日期的HTML代码,它是一款可直接运行的桌面美化工具,能定时更换背景并叠加当前日期。

如何编写自动切换壁纸并日期

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">动态壁纸 · 日期切换</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            min-height: 100vh;
            background: #0b0d15;
            display: flex;
            justify-content: center;
            align-items: center;
            font-family: 'Segoe UI', Roboto, system-ui, -apple-system, sans-serif;
            padding: 16px;
        }
        /* 卡片 — 模拟桌面壁纸预览 */
        .wallpaper-card {
            position: relative;
            width: 100%;
            max-width: 1100px;
            aspect-ratio: 16 / 9;
            border-radius: 36px;
            overflow: hidden;
            box-shadow: 0 30px 50px rgba(0, 0, 0, 0.7), 0 0 0 1px rgba(255, 255, 255, 0.05);
            transition: box-shadow 0.3s ease;
            background: #1e2128;
        }
        .wallpaper-card:hover {
            box-shadow: 0 40px 70px rgba(0, 0, 0, 0.9), 0 0 0 1px rgba(255, 255, 255, 0.08);
        }
        /* 壁纸图层 —— 背景切换由 JS 控制 */
        .wallpaper-layer {
            position: absolute;
            inset: 0;
            width: 100%;
            height: 100%;
            background-size: cover;
            background-position: center center;
            background-repeat: no-repeat;
            transition: opacity 0.8s cubic-bezier(0.23, 1, 0.32, 1);
            opacity: 1;
            will-change: opacity;
            /* 优雅降级:如果图片加载失败,显示纯色 */
            background-color: #2a2f3a;
        }
        /* 玻璃质感日期面板 */
        .date-panel {
            position: absolute;
            bottom: 40px;
            right: 40px;
            background: rgba(10, 14, 23, 0.45);
            backdrop-filter: blur(14px) saturate(180%);
            -webkit-backdrop-filter: blur(14px) saturate(180%);
            padding: 20px 32px;
            border-radius: 60px;
            border: 1px solid rgba(255, 255, 255, 0.18);
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
            display: flex;
            align-items: center;
            gap: 12px;
            pointer-events: none;  /* 让点击穿透,不干扰壁纸交互 */
            user-select: none;
            transition: transform 0.2s ease, background 0.2s;
            transform: translateZ(0);
            letter-spacing: 0.3px;
        }
        .date-icon {
            font-size: 28px;
            line-height: 1;
            opacity: 0.9;
            filter: drop-shadow(0 2px 4px rgba(0,0,0,0.2));
        }
        .date-text {
            color: #ffffff;
            font-size: 28px;
            font-weight: 500;
            text-shadow: 0 2px 10px rgba(0, 0, 0, 0.4);
            white-space: nowrap;
        }
        .date-text span {
            font-weight: 300;
            opacity: 0.7;
            margin-left: 8px;
            font-size: 22px;
        }
        /* 底部控制条 — 干净轻量 */
        .controls {
            position: absolute;
            bottom: 40px;
            left: 40px;
            display: flex;
            gap: 16px;
            align-items: center;
            pointer-events: auto;
            flex-wrap: wrap;
        }
        .controls button {
            background: rgba(20, 25, 40, 0.55);
            backdrop-filter: blur(8px);
            -webkit-backdrop-filter: blur(8px);
            border: 1px solid rgba(255, 255, 255, 0.12);
            color: #f0f4ff;
            padding: 12px 28px;
            border-radius: 50px;
            font-size: 18px;
            font-weight: 450;
            letter-spacing: 0.3px;
            cursor: pointer;
            box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
            transition: background 0.2s, border-color 0.2s, transform 0.1s;
            display: flex;
            align-items: center;
            gap: 8px;
            line-height: 1;
            white-space: nowrap;
            pointer-events: auto;
        }
        .controls button:hover {
            background: rgba(45, 55, 80, 0.7);
            border-color: rgba(255, 255, 255, 0.25);
        }
        .controls button:active {
            transform: scale(0.94);
            background: rgba(20, 25, 40, 0.8);
        }
        .controls .indicator {
            color: rgba(255, 255, 255, 0.6);
            font-size: 16px;
            font-weight: 400;
            background: rgba(0, 0, 0, 0.2);
            backdrop-filter: blur(4px);
            padding: 8px 18px;
            border-radius: 40px;
            border: 1px solid rgba(255, 255, 255, 0.05);
            pointer-events: none;
        }
        /* 移动端适应 */
        @media (max-width: 680px) {
            .wallpaper-card {
                border-radius: 24px;
                aspect-ratio: 4 / 3;  /* 更适应手机竖版 */
            }
            .date-panel {
                bottom: 24px;
                right: 24px;
                padding: 14px 22px;
                border-radius: 40px;
            }
            .date-text {
                font-size: 22px;
            }
            .date-icon {
                font-size: 22px;
            }
            .date-text span {
                font-size: 18px;
            }
            .controls {
                bottom: 24px;
                left: 24px;
                gap: 10px;
            }
            .controls button {
                padding: 10px 20px;
                font-size: 16px;
            }
            .controls .indicator {
                font-size: 14px;
                padding: 6px 14px;
            }
        }
        @media (max-width: 480px) {
            .wallpaper-card {
                aspect-ratio: 4 / 3;
                border-radius: 18px;
            }
            .date-panel {
                bottom: 16px;
                right: 16px;
                padding: 12px 18px;
            }
            .date-text {
                font-size: 18px;
            }
            .date-icon {
                font-size: 18px;
            }
            .date-text span {
                font-size: 15px;
                margin-left: 4px;
            }
            .controls button {
                padding: 8px 14px;
                font-size: 14px;
            }
            .controls .indicator {
                font-size: 12px;
                padding: 5px 10px;
            }
        }
    </style>
</head>
<body>
<div class="wallpaper-card">
    <!-- 壁纸背景层 -->
    <div class="wallpaper-layer" id="wallpaperLayer"></div>
    <!-- 日期面板 (右下) -->
    <div class="date-panel" id="datePanel">
        <span class="date-icon">📅</span>
        <span class="date-text" id="dateDisplay">-- <span>---</span></span>
    </div>
    <!-- 控制区 (左下) -->
    <div class="controls">
        <button id="prevWallpaperBtn" aria-label="上一张">← 上一张</button>
        <span class="indicator" id="counterIndicator">1 / 6</span>
        <button id="nextWallpaperBtn" aria-label="下一张">下一张 →</button>
    </div>
</div>
<script>
    (function() {
        'use strict';
        // ------------------- 壁纸库 (高分辨率优美壁纸) --------------------
        const wallpapers = [
            {
                url: 'https://images.unsplash.com/photo-1506744038136-46273834b3fb?w=1600&q=80',
                name: '山水晨雾'
            },
            {
                url: 'https://images.unsplash.com/photo-1470071459604-7f8e44f1e4b2?w=1600&q=80',
                name: '林间溪流'
            },
            {
                url: 'https://images.unsplash.com/photo-1447752875215-b2761acb3c5d?w=1600&q=80',
                name: '静谧森林'
            },
            {
                url: 'https://images.unsplash.com/photo-1501785888041-af3ef285b470?w=1600&q=80',
                name: '山巅云海'
            },
            {
                url: 'https://images.unsplash.com/photo-1433086966358-54859d0ed716?w=1600&q=80',
                name: '瀑布清幽'
            },
            {
                url: 'https://images.unsplash.com/photo-1569470451076-03ad4ed1af7f?w=1600&q=80',
                name: '暮色山峦'
            }
        ];
        // DOM 引用
        const wallpaperLayer = document.getElementById('wallpaperLayer');
        const dateDisplay = document.getElementById('dateDisplay');
        const prevBtn = document.getElementById('prevWallpaperBtn');
        const nextBtn = document.getElementById('nextWallpaperBtn');
        const counterIndicator = document.getElementById('counterIndicator');
        // 状态
        let currentIndex = 0;          // 0 ~ wallpapers.length-1
        let autoSwitchInterval = null;
        const AUTO_SWITCH_MS = 8000;   // 8秒自动切换
        // ---------------- 辅助函数 ----------------
        function formatDate() {
            const now = new Date();
            const year = now.getFullYear();
            const month = String(now.getMonth() + 1).padStart(2, '0');
            const day = String(now.getDate()).padStart(2, '0');
            // 星期几 (中文)
            const weekdays = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
            const weekday = weekdays[now.getDay()];
            return {
                dateStr: `${year}.${month}.${day}`,
                weekday: weekday
            };
        }
        function updateDateDisplay() {
            const { dateStr, weekday } = formatDate();
            dateDisplay.innerHTML = `${dateStr} <span>${weekday}</span>`;
        }
        // 更新壁纸 (背景)
        function applyWallpaper(index) {
            // 边界保护
            if (index < 0) index = wallpapers.length - 1;
            if (index >= wallpapers.length) index = 0;
            currentIndex = index;
            const wallpaper = wallpapers[currentIndex];
            // 使用 1600w 的 unsplash 图片,并设置背景
            wallpaperLayer.style.backgroundImage = `url('${wallpaper.url}')`;
            // 更新计数器
            counterIndicator.textContent = `${currentIndex + 1} / ${wallpapers.length}`;
            // 可选:预加载附近图片 (改善体验)
            preloadAdjacent(currentIndex);
        }
        // 预加载相邻壁纸 (提前缓存)
        function preloadAdjacent(index) {
            const nextIndex = (index + 1) % wallpapers.length;
            const prevIndex = (index - 1 + wallpapers.length) % wallpapers.length;
            [nextIndex, prevIndex].forEach(i => {
                const img = new Image();
                img.src = wallpapers[i].url;
            });
        }
        // 切换至下一张
        function nextWallpaper() {
            let newIndex = (currentIndex + 1) % wallpapers.length;
            applyWallpaper(newIndex);
            resetAutoSwitch();
        }
        // 切换至上一张
        function prevWallpaper() {
            let newIndex = (currentIndex - 1 + wallpapers.length) % wallpapers.length;
            applyWallpaper(newIndex);
            resetAutoSwitch();
        }
        // ---------------- 自动切换 ----------------
        function startAutoSwitch() {
            if (autoSwitchInterval) clearInterval(autoSwitchInterval);
            autoSwitchInterval = setInterval(() => {
                nextWallpaper();
            }, AUTO_SWITCH_MS);
        }
        function resetAutoSwitch() {
            // 重置计时器:用户手动切换后重新计时
            if (autoSwitchInterval) {
                clearInterval(autoSwitchInterval);
                autoSwitchInterval = null;
            }
            startAutoSwitch();
        }
        // ---------------- 初始化 ----------------
        function init() {
            // 1. 设置初始壁纸 (随机一张)
            const randomIndex = Math.floor(Math.random() * wallpapers.length);
            applyWallpaper(randomIndex);
            // 2. 显示当前日期
            updateDateDisplay();
            // 3. 监听日期更新 (每分钟更新一次)
            setInterval(updateDateDisplay, 60000); // 每分钟校正一次
            // 4. 绑定按钮事件
            prevBtn.addEventListener('click', prevWallpaper);
            nextBtn.addEventListener('click', nextWallpaper);
            // 5. 键盘支持 (左右方向键)
            window.addEventListener('keydown', (e) => {
                if (e.key === 'ArrowLeft') {
                    e.preventDefault();
                    prevWallpaper();
                } else if (e.key === 'ArrowRight') {
                    e.preventDefault();
                    nextWallpaper();
                }
            });
            // 6. 启动自动切换
            startAutoSwitch();
            // 7. 窗口加载完毕后预加载所有壁纸 (提升后续切换流畅度)
            window.addEventListener('load', () => {
                wallpapers.forEach((wp, idx) => {
                    if (idx !== currentIndex) { // 当前已经加载, 额外预加载其余
                        const img = new Image();
                        img.src = wp.url;
                    }
                });
            });
            // (可选) 页面可见性变化时重置计时器 (用户切回时保证稳定)
            document.addEventListener('visibilitychange', () => {
                if (!document.hidden) {
                    resetAutoSwitch();
                    // 同时刷新一下日期 (可能切回时日期已变)
                    updateDateDisplay();
                }
            });
        }
        // 启动
        init();
    })();
</script>
</body>
</html>

壁纸切换与日期显示机制

您可以通过手动操作或让程序自动运行,来体验壁纸的循环切换和实时日期显示。

  • 壁纸库与切换:代码内置了六张精选的高清风景壁纸,您可以通过点击左下角的“上一张/下一张”按钮,或直接使用键盘的 和 方向键来手动切换壁纸。
  • 自动轮播:页面加载后,壁纸会每隔 8秒 自动切换至下一张,形成循环播放效果,当您手动切换壁纸时,自动轮播的计时器会重置,确保您的操作优先。
  • 日期与交互反馈:屏幕右下角会清晰显示当前的 年、月、日及星期,您切换壁纸时,左下角的计数器会同步更新当前壁纸的序号(3 / 6”),方便您了解浏览进度。

优化建议: 您可以根据喜好替换 wallpapers 数组中的图片链接,数组内每个对象包含 urlname,您只需修改 url 为高清图片地址即可更新壁纸库。

抱歉,评论功能暂时关闭!