首页 / 应用软件 / 一步步教你,在WordPress中添加网站暗黑模式切换与个性化主题工具

一步步教你,在WordPress中添加网站暗黑模式切换与个性化主题工具

一步步教你,在WordPress中添加网站暗黑模式切换与个性化主题工具

引言:为什么网站需要暗黑模式与个性化主题工具?

在当今互联网时代,用户体验已成为网站成功的关键因素之一。随着用户对个性化体验需求的增加,以及健康用眼意识的提升,暗黑模式已成为现代网站的标配功能。根据2023年的一项调查显示,超过82%的用户表示更喜欢使用支持暗黑模式的网站,尤其是在夜间浏览时。

WordPress作为全球最流行的内容管理系统,拥有超过40%的市场份额,但其默认主题往往缺乏现代化的暗黑模式切换功能。通过代码二次开发,我们不仅可以为WordPress网站添加暗黑模式,还能创建一套完整的个性化主题工具,让用户根据自己的偏好调整网站外观。

本文将详细介绍如何通过WordPress代码二次开发,实现暗黑模式切换与个性化主题工具,让你的网站在众多WordPress站点中脱颖而出。

第一部分:准备工作与环境配置

1.1 创建子主题

在进行任何WordPress代码修改之前,最佳实践是创建一个子主题。这样可以确保你的修改不会在主题更新时丢失。

/*
Theme Name: 我的个性化主题
Template: twentytwentythree
Version: 1.0.0
Description: 添加暗黑模式与个性化工具的WordPress子主题
*/

在WordPress的wp-content/themes目录下创建新文件夹"my-custom-theme",并创建style.css文件,添加上述代码。然后创建functions.php文件,用于添加功能代码。

1.2 设置开发环境

确保你的开发环境满足以下要求:

  • WordPress 5.0或更高版本
  • PHP 7.4或更高版本
  • 支持JavaScript的现代浏览器
  • 代码编辑器(如VS Code、Sublime Text等)

1.3 备份原始文件

在进行任何代码修改前,请务必备份以下文件:

  • 当前主题的functions.php
  • 当前主题的style.css
  • 当前主题的JavaScript文件

第二部分:实现暗黑模式切换功能

2.1 理解暗黑模式的实现原理

暗黑模式的核心是通过CSS变量或类名切换来改变网站的颜色方案。我们将采用以下两种方法结合的方式:

  1. CSS变量方法:定义两套颜色变量(亮色和暗色)
  2. 类名切换方法:通过JavaScript在body标签上添加或移除"dark-mode"类

2.2 创建CSS颜色变量系统

在子主题的style.css文件中,添加CSS变量定义:

:root {
  /* 亮色主题变量 */
  --primary-color: #3498db;
  --secondary-color: #2ecc71;
  --background-color: #ffffff;
  --text-color: #333333;
  --header-bg: #f8f9fa;
  --border-color: #e0e0e0;
  --card-bg: #ffffff;
  --shadow-color: rgba(0, 0, 0, 0.1);
}

.dark-mode {
  /* 暗色主题变量 */
  --primary-color: #5dade2;
  --secondary-color: #58d68d;
  --background-color: #121212;
  --text-color: #e0e0e0;
  --header-bg: #1e1e1e;
  --border-color: #333333;
  --card-bg: #1e1e1e;
  --shadow-color: rgba(0, 0, 0, 0.3);
}

/* 应用CSS变量到网站元素 */
body {
  background-color: var(--background-color);
  color: var(--text-color);
  transition: background-color 0.3s ease, color 0.3s ease;
}

header {
  background-color: var(--header-bg);
  border-bottom: 1px solid var(--border-color);
}

.card {
  background-color: var(--card-bg);
  box-shadow: 0 2px 10px var(--shadow-color);
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
}

2.3 创建暗黑模式切换开关

在主题的合适位置(通常是页眉或页脚)添加暗黑模式切换按钮。首先,在functions.php中添加切换按钮的HTML代码:

function add_dark_mode_switch() {
    echo '<button id="dark-mode-toggle" class="dark-mode-toggle" aria-label="切换暗黑模式">
            <span class="toggle-icon light-icon">☀️</span>
            <span class="toggle-icon dark-icon">🌙</span>
          </button>';
}
add_action('wp_body_open', 'add_dark_mode_switch');

2.4 添加切换功能的JavaScript

创建新的JavaScript文件(如dark-mode.js)并添加到主题中:

// dark-mode.js
document.addEventListener('DOMContentLoaded', function() {
    const darkModeToggle = document.getElementById('dark-mode-toggle');
    const body = document.body;
    
    // 检查用户之前的偏好设置
    const prefersDarkScheme = window.matchMedia('(prefers-color-scheme: dark)');
    const savedTheme = localStorage.getItem('theme');
    
    // 初始化主题
    function initTheme() {
        if (savedTheme === 'dark' || (!savedTheme && prefersDarkScheme.matches)) {
            body.classList.add('dark-mode');
            updateToggleButton(true);
        } else {
            body.classList.remove('dark-mode');
            updateToggleButton(false);
        }
    }
    
    // 更新切换按钮状态
    function updateToggleButton(isDarkMode) {
        if (isDarkMode) {
            darkModeToggle.setAttribute('aria-label', '切换到亮色模式');
            darkModeToggle.classList.add('active');
        } else {
            darkModeToggle.setAttribute('aria-label', '切换到暗黑模式');
            darkModeToggle.classList.remove('active');
        }
    }
    
    // 切换主题
    function toggleTheme() {
        if (body.classList.contains('dark-mode')) {
            body.classList.remove('dark-mode');
            localStorage.setItem('theme', 'light');
            updateToggleButton(false);
        } else {
            body.classList.add('dark-mode');
            localStorage.setItem('theme', 'dark');
            updateToggleButton(true);
        }
    }
    
    // 监听系统主题变化
    prefersDarkScheme.addEventListener('change', function(e) {
        if (!localStorage.getItem('theme')) {
            if (e.matches) {
                body.classList.add('dark-mode');
                updateToggleButton(true);
            } else {
                body.classList.remove('dark-mode');
                updateToggleButton(false);
            }
        }
    });
    
    // 绑定点击事件
    darkModeToggle.addEventListener('click', toggleTheme);
    
    // 初始化
    initTheme();
});

在functions.php中注册并加载这个JavaScript文件:

function enqueue_dark_mode_scripts() {
    wp_enqueue_script(
        'dark-mode-script',
        get_stylesheet_directory_uri() . '/js/dark-mode.js',
        array(),
        '1.0.0',
        true
    );
}
add_action('wp_enqueue_scripts', 'enqueue_dark_mode_scripts');

2.5 添加切换按钮样式

为暗黑模式切换按钮添加CSS样式:

.dark-mode-toggle {
    position: fixed;
    bottom: 30px;
    right: 30px;
    width: 60px;
    height: 60px;
    border-radius: 50%;
    background-color: var(--primary-color);
    border: none;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4px 12px var(--shadow-color);
    z-index: 9999;
    transition: all 0.3s ease;
}

.dark-mode-toggle:hover {
    transform: scale(1.1);
    box-shadow: 0 6px 16px var(--shadow-color);
}

.toggle-icon {
    font-size: 24px;
    position: absolute;
    transition: opacity 0.3s ease, transform 0.3s ease;
}

.dark-icon {
    opacity: 0;
    transform: rotate(90deg);
}

.light-icon {
    opacity: 1;
    transform: rotate(0);
}

.dark-mode-toggle.active .dark-icon {
    opacity: 1;
    transform: rotate(0);
}

.dark-mode-toggle.active .light-icon {
    opacity: 0;
    transform: rotate(-90deg);
}

第三部分:创建个性化主题工具面板

3.1 设计个性化工具面板界面

我们将创建一个滑出式面板,用户可以通过它调整网站的各种视觉设置。首先,在functions.php中添加面板HTML结构:

function add_theme_customizer_panel() {
    ?>
    <div id="theme-customizer" class="theme-customizer">
        <button id="customizer-toggle" class="customizer-toggle" aria-label="打开主题定制面板">
            <span class="customizer-icon">⚙️</span>
        </button>
        
        <div class="customizer-panel">
            <div class="customizer-header">
                <h3>主题定制</h3>
                <button id="close-customizer" class="close-customizer" aria-label="关闭面板">×</button>
            </div>
            
            <div class="customizer-body">
                <div class="customizer-section">
                    <h4>颜色主题</h4>
                    
                    <div class="color-option">
                        <label for="primary-color">主色调</label>
                        <input type="color" id="primary-color" value="#3498db">
                    </div>
                    
                    <div class="color-option">
                        <label for="secondary-color">辅助色</label>
                        <input type="color" id="secondary-color" value="#2ecc71">
                    </div>
                    
                    <div class="color-option">
                        <label for="background-color">背景色</label>
                        <input type="color" id="background-color" value="#ffffff">
                    </div>
                </div>
                
                <div class="customizer-section">
                    <h4>字体设置</h4>
                    
                    <div class="font-option">
                        <label for="font-family">字体家族</label>
                        <select id="font-family">
                            <option value="'Helvetica Neue', Arial, sans-serif">系统默认</option>
                            <option value="'Roboto', sans-serif">Roboto</option>
                            <option value="'Open Sans', sans-serif">Open Sans</option>
                            <option value="'Montserrat', sans-serif">Montserrat</option>
                            <option value="'Georgia', serif">Georgia</option>
                        </select>
                    </div>
                    
                    <div class="font-option">
                        <label for="font-size">基础字号</label>
                        <input type="range" id="font-size" min="12" max="20" value="16">
                        <span id="font-size-value">16px</span>
                    </div>
                </div>
                
                <div class="customizer-section">
                    <h4>布局设置</h4>
                    
                    <div class="layout-option">
                        <label for="layout-width">内容宽度</label>
                        <input type="range" id="layout-width" min="800" max="1400" value="1200">
                        <span id="layout-width-value">1200px</span>
                    </div>
                    
                    <div class="layout-option">
                        <label>
                            <input type="checkbox" id="rounded-corners" checked>
                            圆角元素
                        </label>
                    </div>
                </div>
                
                <div class="customizer-actions">
                    <button id="reset-customizations" class="button-secondary">重置设置</button>
                    <button id="save-customizations" class="button-primary">保存设置</button>
                </div>
            </div>
        </div>
    </div>
    <?php
}
add_action('wp_footer', 'add_theme_customizer_panel');

3.2 添加个性化工具面板样式

为个性化工具面板添加CSS样式:

.theme-customizer {
    position: fixed;
    top: 0;
    right: 0;
    z-index: 10000;
}

.customizer-toggle {
    position: fixed;
    top: 50%;
    right: 0;
    transform: translateY(-50%);
    background-color: var(--primary-color);
    color: white;
    border: none;
    border-radius: 5px 0 0 5px;
    padding: 15px 10px;
    cursor: pointer;
    font-size: 20px;
    transition: all 0.3s ease;
    box-shadow: -2px 0 10px var(--shadow-color);
}

.customizer-toggle:hover {
    padding-right: 15px;
}

.customizer-panel {
    position: fixed;
    top: 0;
    right: -400px;
    width: 380px;
    height: 100vh;
    background-color: var(--card-bg);
    box-shadow: -5px 0 15px var(--shadow-color);
    transition: right 0.3s ease;
    overflow-y: auto;
}

.customizer-panel.open {
    right: 0;
}

.customizer-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px;
    border-bottom: 1px solid var(--border-color);
}

.customizer-header h3 {
    margin: 0;
    color: var(--text-color);
}

.close-customizer {
    background: none;
    border: none;
    font-size: 28px;
    cursor: pointer;
    color: var(--text-color);
    line-height: 1;
}

.customizer-body {
    padding: 20px;
}

.customizer-section {
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 1px solid var(--border-color);
}

.customizer-section h4 {
    margin-top: 0;
    margin-bottom: 15px;
    color: var(--text-color);
}

.color-option,
.font-option,
.layout-option {
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.color-option label,
.font-option label,
.layout-option label {
    color: var(--text-color);
    margin-right: 15px;
}

.color-option input[type="color"] {
    width: 50px;
    height: 40px;
    border: 2px solid var(--border-color);
    border-radius: 4px;
    cursor: pointer;
}

.font-option select,
.font-option input[type="range"],
.layout-option input[type="range"] {
    flex-grow: 1;
    max-width: 200px;
}

.customizer-actions {
    display: flex;
    justify-content: space-between;
    margin-top: 30px;
}

.button-primary,
.button-secondary {
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-weight: bold;
    transition: all 0.2s ease;
}

.button-primary {
    background-color: var(--primary-color);
    color: white;
}

.button-secondary {
    background-color: var(--border-color);
    color: var(--text-color);
}

.button-primary:hover,
.button-secondary:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px var(--shadow-color);
}

3.3 实现个性化设置功能

创建customizer.js文件,实现个性化设置功能:

// customizer.js
document.addEventListener('DOMContentLoaded', function() {
    const customizerToggle = document.getElementById('customizer-toggle');
    const closeCustomizer = document.getElementById('close-customizer');
    const customizerPanel = document.querySelector('.customizer-panel');
    const saveButton = document.getElementById('save-customizations');
    const resetButton = document.getElementById('reset-customizations');
    
    // 获取所有可定制的选项
    const primaryColorInput = document.getElementById('primary-color');
    const secondaryColorInput = document.getElementById('secondary-color');
    const backgroundColorInput = document.getElementById('background-color');
    const fontFamilySelect = document.getElementById('font-family');
    const fontSizeInput = document.getElementById('font-size');
    const fontSizeValue = document.getElementById('font-size-value');
    const layoutWidthInput = document.getElementById('layout-width');
    const layoutWidthValue = document.getElementById('layout-width-value');
    const roundedCornersCheckbox = document.getElementById('rounded-corners');
    
    // 初始化面板状态
    function initCustomizer() {
        // 从localStorage加载保存的设置
        const savedSettings = JSON.parse(localStorage.getItem('themeSettings')) || {};
        
        // 设置输入控件的值
        if (savedSettings.primaryColor) {
            primaryColorInput.value = savedSettings.primaryColor;
            updateCSSVariable('--primary-color', savedSettings.primaryColor);
        }
        
        if (savedSettings.secondaryColor) {
            secondaryColorInput.value = savedSettings.secondaryColor;
            updateCSSVariable('--secondary-color', savedSettings.secondaryColor);
        }
        
        if (savedSettings.backgroundColor) {
            backgroundColorInput.value = savedSettings.backgroundColor;
            updateCSSVariable('--background-color', savedSettings.backgroundColor);
        }
        
        if (savedSettings.fontFamily) {
            fontFamilySelect.value = savedSettings.fontFamily;
            updateCSSVariable('--font-family', savedSettings.fontFamily);
        }
        
        if (savedSettings.fontSize) {
            fontSizeInput.value = savedSettings.fontSize;
            fontSizeValue.textContent = savedSettings.fontSize + 'px';
            updateCSSVariable('--base-font-size', savedSettings.fontSize + 'px');
        }
        
        if (savedSettings.layoutWidth) {
            layoutWidthInput.value = savedSettings.layoutWidth;
            layoutWidthValue.textContent = savedSettings.layoutWidth + 'px';
            updateCSSVariable('--container-width', savedSettings.layoutWidth + 'px');
        }
        
        if (savedSettings.roundedCorners !== undefined) {
            roundedCornersCheckbox.checked = savedSettings.roundedCorners;
            toggleRoundedCorners(savedSettings.roundedCorners);
        }
    }
    
    // 更新CSS变量
    function updateCSSVariable(variable, value) {
        document.documentElement.style.setProperty(variable, value);
    }
    
    // 切换圆角样式
    function toggleRoundedCorners(enabled) {
        document.body.classList.add('rounded-elements');
    } else {
        document.body.classList.remove('rounded-elements');
    }
}

// 保存设置到localStorage
function saveSettings() {
    const settings = {
        primaryColor: primaryColorInput.value,
        secondaryColor: secondaryColorInput.value,
        backgroundColor: backgroundColorInput.value,
        fontFamily: fontFamilySelect.value,
        fontSize: parseInt(fontSizeInput.value),
        layoutWidth: parseInt(layoutWidthInput.value),
        roundedCorners: roundedCornersCheckbox.checked
    };
    
    localStorage.setItem('themeSettings', JSON.stringify(settings));
    
    // 显示保存成功的提示
    showNotification('设置已保存!', 'success');
}

// 重置所有设置
function resetSettings() {
    // 清除localStorage中的设置
    localStorage.removeItem('themeSettings');
    
    // 重置CSS变量为默认值
    const root = document.documentElement;
    root.style.removeProperty('--primary-color');
    root.style.removeProperty('--secondary-color');
    root.style.removeProperty('--background-color');
    root.style.removeProperty('--font-family');
    root.style.removeProperty('--base-font-size');
    root.style.removeProperty('--container-width');
    
    // 重置输入控件
    primaryColorInput.value = '#3498db';
    secondaryColorInput.value = '#2ecc71';
    backgroundColorInput.value = '#ffffff';
    fontFamilySelect.value = "'Helvetica Neue', Arial, sans-serif";
    fontSizeInput.value = 16;
    fontSizeValue.textContent = '16px';
    layoutWidthInput.value = 1200;
    layoutWidthValue.textContent = '1200px';
    roundedCornersCheckbox.checked = true;
    toggleRoundedCorners(true);
    
    // 显示重置成功的提示
    showNotification('设置已重置为默认值!', 'info');
}

// 显示通知
function showNotification(message, type) {
    // 移除已存在的通知
    const existingNotification = document.querySelector('.customizer-notification');
    if (existingNotification) {
        existingNotification.remove();
    }
    
    // 创建新通知
    const notification = document.createElement('div');
    notification.className = `customizer-notification ${type}`;
    notification.textContent = message;
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 3秒后自动移除
    setTimeout(() => {
        notification.classList.add('fade-out');
        setTimeout(() => notification.remove(), 300);
    }, 3000);
}

// 事件监听器
customizerToggle.addEventListener('click', () => {
    customizerPanel.classList.add('open');
});

closeCustomizer.addEventListener('click', () => {
    customizerPanel.classList.remove('open');
});

// 实时更新颜色预览
primaryColorInput.addEventListener('input', (e) => {
    updateCSSVariable('--primary-color', e.target.value);
});

secondaryColorInput.addEventListener('input', (e) => {
    updateCSSVariable('--secondary-color', e.target.value);
});

backgroundColorInput.addEventListener('input', (e) => {
    updateCSSVariable('--background-color', e.target.value);
});

// 实时更新字体设置
fontFamilySelect.addEventListener('change', (e) => {
    updateCSSVariable('--font-family', e.target.value);
});

fontSizeInput.addEventListener('input', (e) => {
    const value = e.target.value;
    fontSizeValue.textContent = value + 'px';
    updateCSSVariable('--base-font-size', value + 'px');
});

// 实时更新布局设置
layoutWidthInput.addEventListener('input', (e) => {
    const value = e.target.value;
    layoutWidthValue.textContent = value + 'px';
    updateCSSVariable('--container-width', value + 'px');
});

roundedCornersCheckbox.addEventListener('change', (e) => {
    toggleRoundedCorners(e.target.checked);
});

// 保存和重置按钮
saveButton.addEventListener('click', saveSettings);
resetButton.addEventListener('click', resetSettings);

// 初始化定制器
initCustomizer();
});

在functions.php中注册并加载这个JavaScript文件:

function enqueue_customizer_scripts() {
    wp_enqueue_script(
        'customizer-script',
        get_stylesheet_directory_uri() . '/js/customizer.js',
        array(),
        '1.0.0',
        true
    );
}
add_action('wp_enqueue_scripts', 'enqueue_customizer_scripts');

3.4 添加通知样式

为个性化工具面板的通知功能添加CSS样式:

.customizer-notification {
    position: fixed;
    bottom: 100px;
    right: 30px;
    padding: 15px 25px;
    border-radius: 8px;
    color: white;
    font-weight: bold;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    z-index: 10001;
    animation: slideIn 0.3s ease;
    max-width: 300px;
}

.customizer-notification.success {
    background-color: #2ecc71;
}

.customizer-notification.info {
    background-color: #3498db;
}

.customizer-notification.error {
    background-color: #e74c3c;
}

.customizer-notification.fade-out {
    animation: fadeOut 0.3s ease forwards;
}

@keyframes slideIn {
    from {
        transform: translateX(100%);
        opacity: 0;
    }
    to {
        transform: translateX(0);
        opacity: 1;
    }
}

@keyframes fadeOut {
    from {
        transform: translateX(0);
        opacity: 1;
    }
    to {
        transform: translateX(100%);
        opacity: 0;
    }
}

第四部分:集成常用互联网小工具

4.1 添加阅读进度条

阅读进度条是许多现代网站的实用功能,可以显示用户在页面上的阅读进度。

在functions.php中添加阅读进度条:

function add_reading_progress_bar() {
    echo '<div id="reading-progress" class="reading-progress">
            <div class="reading-progress-bar"></div>
          </div>';
}
add_action('wp_body_open', 'add_reading_progress_bar');

添加阅读进度条样式:

.reading-progress {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 4px;
    background-color: transparent;
    z-index: 9998;
}

.reading-progress-bar {
    height: 100%;
    background-color: var(--primary-color);
    width: 0%;
    transition: width 0.2s ease;
}

添加阅读进度条JavaScript功能:

// reading-progress.js
document.addEventListener('DOMContentLoaded', function() {
    const progressBar = document.querySelector('.reading-progress-bar');
    
    if (!progressBar) return;
    
    function updateReadingProgress() {
        const windowHeight = window.innerHeight;
        const documentHeight = document.documentElement.scrollHeight - windowHeight;
        const scrolled = window.scrollY;
        
        const progress = (scrolled / documentHeight) * 100;
        progressBar.style.width = progress + '%';
    }
    
    // 监听滚动事件
    window.addEventListener('scroll', updateReadingProgress);
    
    // 初始化
    updateReadingProgress();
});

4.2 添加回到顶部按钮

回到顶部按钮是长页面中非常实用的功能。

在functions.php中添加回到顶部按钮:

function add_back_to_top_button() {
    echo '<button id="back-to-top" class="back-to-top" aria-label="回到顶部">↑</button>';
}
add_action('wp_footer', 'add_back_to_top_button');

添加回到顶部按钮样式:

.back-to-top {
    position: fixed;
    bottom: 100px;
    right: 30px;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background-color: var(--primary-color);
    color: white;
    border: none;
    cursor: pointer;
    display: none;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    box-shadow: 0 4px 12px var(--shadow-color);
    z-index: 9997;
    transition: all 0.3s ease;
}

.back-to-top.visible {
    display: flex;
}

.back-to-top:hover {
    transform: translateY(-5px);
    box-shadow: 0 6px 16px var(--shadow-color);
}

添加回到顶部按钮JavaScript功能:

// back-to-top.js
document.addEventListener('DOMContentLoaded', function() {
    const backToTopButton = document.getElementById('back-to-top');
    
    if (!backToTopButton) return;
    
    function toggleBackToTopButton() {
        if (window.scrollY > 300) {
            backToTopButton.classList.add('visible');
        } else {
            backToTopButton.classList.remove('visible');
        }
    }
    
    function scrollToTop() {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    }
    
    // 监听滚动事件
    window.addEventListener('scroll', toggleBackToTopButton);
    
    // 点击事件
    backToTopButton.addEventListener('click', scrollToTop);
    
    // 初始化
    toggleBackToTopButton();
});

4.3 添加代码高亮功能

对于技术博客或教程网站,代码高亮是必不可少的功能。

首先,在functions.php中集成Prism.js代码高亮库:

function enqueue_prism_assets() {
    // Prism.js核心CSS
    wp_enqueue_style(
        'prism-css',
        'https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css',
        array(),
        '1.29.0'
    );
    
    // Prism.js核心JS
    wp_enqueue_script(
        'prism-js',
        'https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/prism.min.js',
        array(),
        '1.29.0',
        true
    );
    
    // 添加常用语言支持
    wp_enqueue_script(
        'prism-js-php',
        'https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-php.min.js',
        array('prism-js'),
        '1.29.0',
        true
    );
    
    wp_enqueue_script(
        'prism-js-javascript',
        'https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-javascript.min.js',
        array('prism-js'),
        '1.29.0',
        true
    );
    
    wp_enqueue_script(
        'prism-js-css',
        'https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-css.min.js',
        array('prism-js'),
        '1.29.0',
        true
    );
}
add_action('wp_enqueue_scripts', 'enqueue_prism_assets');

4.4 添加复制代码按钮

为代码块添加复制功能,提升用户体验。

添加复制代码按钮的JavaScript功能:

// copy-code.js
document.addEventListener('DOMContentLoaded', function() {
    // 为所有代码块添加复制按钮
    document.querySelectorAll('pre code').forEach(function(codeBlock) {
        // 创建复制按钮
        const copyButton = document.createElement('button');
        copyButton.className = 'copy-code-button';
        copyButton.textContent = '复制';
        copyButton.setAttribute('aria-label', '复制代码');
        
        // 将按钮添加到代码块容器
        const pre = codeBlock.parentNode;
        if (pre.tagName === 'PRE') {
            pre.style.position = 'relative';
            pre.appendChild(copyButton);
        }
        
        // 复制功能
        copyButton.addEventListener('click', function() {
            const textToCopy = codeBlock.textContent;
            
            navigator.clipboard.writeText(textToCopy).then(function() {
                // 复制成功反馈
                copyButton.textContent = '已复制!';
                copyButton.classList.add('copied');
                
                setTimeout(function() {
                    copyButton.textContent = '复制';
                    copyButton.classList.remove('copied');
                }, 2000);
            }).catch(function(err) {
                console.error('复制失败: ', err);
                copyButton.textContent = '复制失败';
            });
        });
    });
});

添加复制按钮样式:

.copy-code-button {
    position: absolute;
    top: 10px;
    right: 10px;
    padding: 5px 10px;
    background-color: var(--primary-color);
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 12px;
    opacity: 0;
    transition: opacity 0.3s ease;
}

pre:hover .copy-code-button {
    opacity: 1;
}

.copy-code-button.copied {
    background-color: #2ecc71;
}

第五部分:优化与高级功能

5.1 添加主题设置导入/导出功能

允许用户导出自己的主题设置,并在其他设备上导入。

在个性化工具面板中添加导入/导出功能:

// 在customizer-body部分添加以下代码
<div class="customizer-section">
    <h4>导入/导出设置</h4>
    
    <div class="import-export-option">
        <button id="export-settings" class="button-secondary">导出设置</button>
        <button id="import-settings" class="button-secondary">导入设置</button>
        <input type="file" id="import-file" accept=".json" style="display: none;">
    </div>
    
    <div id="export-result" class="export-result" style="display: none;">
        <textarea id="export-data" readonly rows="4"></textarea>
        <button id="copy-export" class="button-secondary">复制JSON</button>
    </div>
</div>

添加导入/导出功能的JavaScript:

// import-export.js
document.addEventListener('DOMContentLoaded', function() {
    const exportButton = document.getElementById('export-settings');
    const importButton = document.getElementById('import-settings');
    const importFileInput = document.getElementById('import-file');
    const exportResult = document.getElementById('export-result');
    const exportData = document.getElementById('export-data');
    const copyExportButton = document.getElementById('copy-export');
    
    // 导出设置
    exportButton.addEventListener('click', function() {
        const settings = JSON.parse(localStorage.getItem('themeSettings')) || {};
        const settingsJSON = JSON.stringify(settings, null, 2);
        
        exportData.value = settingsJSON;
        exportResult.style.display = 'block';
        
        // 自动滚动到导出结果
        exportResult.scrollIntoView({ behavior: 'smooth' });
    });
    
    // 复制导出数据
    copyExportButton.addEventListener('click', function() {
        exportData.select();
        document.execCommand('copy');
        
        // 显示复制成功提示
        showNotification('设置已复制到剪贴板!', 'success');
    });
    
    // 导入设置
    importButton.addEventListener('click', function() {
        importFileInput.click();
    });
    
    importFileInput.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (!file) return;
        
        const reader = new FileReader();
        
        reader.onload = function(event) {
            try {
                const settings = JSON.parse(event.target.result);
                
                // 验证设置格式
                if (typeof settings === 'object' && settings !== null) {
                    // 保存设置到localStorage
                    localStorage.setItem('themeSettings', JSON.stringify(settings));
                    
                    // 应用新设置
                    applySettings(settings);
                    
                    // 显示成功提示
                    showNotification('设置导入成功!', 'success');
                } else {
                    throw new Error('无效的设置文件格式');
                }
            } catch (error) {
                showNotification('导入失败:' + error.message, 'error');
            }
        };
        
        reader.readAsText(file);
        
        // 重置文件输入
        importFileInput.value = '';
    });
    
    // 应用设置函数
    function applySettings(settings) {
        // 更新所有输入控件
        if (settings.primaryColor) {
            primaryColorInput.value = settings.primaryColor;
            updateCSSVariable('--primary-color', settings.primaryColor);
        }
        
        if (settings.secondaryColor) {
            secondaryColorInput.value = settings.secondaryColor;
            updateCSSVariable('--secondary-color', settings.secondaryColor);
        }
        
        if (settings.backgroundColor) {
            backgroundColorInput.value = settings.backgroundColor;
            updateCSSVariable('--background-color', settings.backgroundColor);
        }
        
        if (settings.fontFamily) {
            fontFamilySelect.value = settings.fontFamily;
            updateCSSVariable('--font-family', settings.fontFamily);
        }
        
        if (settings.fontSize) {
            fontSizeInput.value = settings.fontSize;
            fontSizeValue.textContent = settings.fontSize + 'px';
            updateCSSVariable('--base-font-size', settings.fontSize + 'px');
        }
        
        if (settings.layoutWidth) {
            layoutWidthInput.value = settings.layoutWidth;
            layoutWidthValue.textContent = settings.layoutWidth + 'px';
            updateCSSVariable('--container-width', settings.layoutWidth + 'px');
        }
        
        if (settings.roundedCorners !== undefined) {
            roundedCornersCheckbox.checked = settings.roundedCorners;
            toggleRoundedCorners(settings.roundedCorners);
        }
    }
});

5.2 添加键盘快捷键支持

为高级用户添加键盘快捷键,提升操作效率。

添加键盘快捷键功能:

// keyboard-shortcuts.js
document.addEventListener('DOMContentLoaded', function() {
    // 键盘快捷键映射
    const shortcuts = {
        // 切换暗黑模式: Ctrl+Shift+D
        'toggleDarkMode': {
            key: 'D',
            ctrlKey: true,
            shiftKey: true,
            action: function() {
                const darkModeToggle = document.getElementById('dark-mode-toggle');
                if (darkModeToggle) darkModeToggle.click();
            }
        },
        
        // 打开/关闭定制面板: Ctrl+Shift+C
        'toggleCustomizer': {
            key: 'C',
            ctrlKey: true,
本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/5220.html

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

工作时间:周一至周五,9:00-17:30,节假日休息
返回顶部