文章目录
-
- 在当今互联网时代,用户体验已成为网站成功的关键因素之一。根据研究,网站访问者平均只花费15秒决定是否继续浏览一个网站。在这短暂的时间内,能否快速找到联系方式和反馈渠道直接影响着转化率和用户满意度。 浮动在线联系与反馈窗口作为一种常见的互联网小工具,具有以下优势: 即时可访问性:无论用户滚动到页面哪个位置,联系入口始终可见 提升转化率:减少用户寻找联系方式的步骤,提高咨询可能性 增强用户体验:提供便捷的反馈渠道,收集用户意见 专业形象展示:展示企业的在线服务能力和响应速度 本文将详细指导您如何通过WordPress代码二次开发,实现一个功能完善、美观实用的浮动在线联系与反馈窗口。
-
- 在开始之前,请确保您的WordPress环境满足以下要求: WordPress版本:5.0或更高 PHP版本:7.2或更高(推荐7.4+) 基本的HTML、CSS、JavaScript知识 代码编辑器(如VS Code、Sublime Text等) FTP客户端或WordPress文件管理器访问权限
- 为了避免主题更新导致自定义代码丢失,我们强烈建议使用子主题进行开发: 在WordPress的wp-content/themes/目录下创建新文件夹,命名为yourtheme-child(将"yourtheme"替换为您的主题名称) 在子主题文件夹中创建style.css文件,添加以下内容: /* Theme Name: YourTheme Child Theme URI: https://example.com/ Description: Child theme for adding floating contact widget Author: Your Name Author URI: https://example.com/ Template: yourtheme Version: 1.0.0 */ 创建functions.php文件,添加以下代码启用子主题: <?php add_action('wp_enqueue_scripts', 'my_child_theme_enqueue_styles'); function my_child_theme_enqueue_styles() { wp_enqueue_style('parent-style', get_template_directory_uri() . '/style.css'); wp_enqueue_style('child-style', get_stylesheet_directory_uri() . '/style.css', array('parent-style')); } ?> 在WordPress后台"外观"→"主题"中激活您的子主题
-
- 在子主题文件夹中创建floating-contact.php文件,添加以下HTML结构: <?php /** * Floating Contact Widget HTML Structure */ function floating_contact_html() { ob_start(); ?> <!-- 浮动联系窗口主容器 --> <div id="floating-contact-widget" class="floating-contact-container"> <!-- 主按钮 --> <div class="floating-contact-main-btn"> <span class="contact-icon">💬</span> <span class="contact-text">联系我们</span> </div> <!-- 展开面板 --> <div class="floating-contact-panel"> <div class="panel-header"> <h3>在线联系</h3> <button class="close-panel">×</button> </div> <div class="panel-content"> <!-- 联系渠道选择 --> <div class="contact-methods"> <div class="method-item" data-method="chat"> <div class="method-icon">💬</div> <div class="method-info"> <h4>在线聊天</h4> <p>即时响应,快速解答</p> </div> </div> <div class="method-item" data-method="phone"> <div class="method-icon">📞</div> <div class="method-info"> <h4>电话联系</h4> <p>400-123-4567</p> </div> </div> <div class="method-item" data-method="email"> <div class="method-icon">✉️</div> <div class="method-info"> <h4>邮件反馈</h4> <p>24小时内回复</p> </div> </div> <div class="method-item" data-method="form"> <div class="method-icon">📝</div> <div class="method-info"> <h4>提交表单</h4> <p>详细问题反馈</p> </div> </div> </div> <!-- 聊天界面 --> <div class="chat-interface" style="display:none;"> <div class="chat-header"> <button class="back-to-methods">←</button> <h4>在线客服</h4> </div> <div class="chat-messages"> <!-- 聊天消息将通过JavaScript动态加载 --> </div> <div class="chat-input-area"> <textarea placeholder="请输入您的问题..." rows="3"></textarea> <button class="send-message">发送</button> </div> </div> <!-- 反馈表单 --> <div class="feedback-form" style="display:none;"> <div class="form-header"> <button class="back-to-methods">←</button> <h4>问题反馈</h4> </div> <form id="feedbackForm"> <div class="form-group"> <label for="feedbackName">姓名 *</label> <input type="text" id="feedbackName" name="name" required> </div> <div class="form-group"> <label for="feedbackEmail">邮箱 *</label> <input type="email" id="feedbackEmail" name="email" required> </div> <div class="form-group"> <label for="feedbackSubject">主题</label> <input type="text" id="feedbackSubject" name="subject"> </div> <div class="form-group"> <label for="feedbackMessage">内容 *</label> <textarea id="feedbackMessage" name="message" rows="5" required></textarea> </div> <div class="form-group"> <button type="submit" class="submit-feedback">提交反馈</button> </div> </form> </div> </div> </div> </div> <?php return ob_get_clean(); } ?>
- 在子主题的style.css文件中添加以下样式: /* 浮动联系窗口基础样式 */ .floating-contact-container { position: fixed; bottom: 30px; right: 30px; z-index: 9999; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif; } /* 主按钮样式 */ .floating-contact-main-btn { background: linear-gradient(135deg, #4a6ee0 0%, #6a11cb 100%); color: white; padding: 15px 20px; border-radius: 50px; cursor: pointer; display: flex; align-items: center; gap: 10px; box-shadow: 0 5px 15px rgba(106, 17, 203, 0.3); transition: all 0.3s ease; user-select: none; } .floating-contact-main-btn:hover { transform: translateY(-3px); box-shadow: 0 8px 20px rgba(106, 17, 203, 0.4); } .contact-icon { font-size: 20px; } .contact-text { font-weight: 600; font-size: 16px; } /* 展开面板样式 */ .floating-contact-panel { position: absolute; bottom: 70px; right: 0; width: 350px; background: white; border-radius: 12px; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15); overflow: hidden; display: none; animation: slideUp 0.3s ease; } @keyframes slideUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } } .panel-header { background: linear-gradient(135deg, #4a6ee0 0%, #6a11cb 100%); color: white; padding: 15px 20px; display: flex; justify-content: space-between; align-items: center; } .panel-header h3 { margin: 0; font-size: 18px; } .close-panel { background: none; border: none; color: white; font-size: 24px; cursor: pointer; line-height: 1; padding: 0; width: 30px; height: 30px; display: flex; align-items: center; justify-content: center; border-radius: 50%; transition: background 0.2s; } .close-panel:hover { background: rgba(255, 255, 255, 0.2); } .panel-content { padding: 20px; } /* 联系方法样式 */ .contact-methods { display: grid; grid-template-columns: 1fr 1fr; gap: 15px; } .method-item { background: #f8f9fa; border-radius: 8px; padding: 15px; cursor: pointer; transition: all 0.2s ease; border: 1px solid #e9ecef; } .method-item:hover { background: #e9ecef; transform: translateY(-2px); box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); } .method-icon { font-size: 24px; margin-bottom: 8px; } .method-info h4 { margin: 0 0 5px 0; font-size: 14px; color: #333; } .method-info p { margin: 0; font-size: 12px; color: #666; } /* 聊天界面样式 */ .chat-interface, .feedback-form { animation: fadeIn 0.3s ease; } @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } } .chat-header, .form-header { display: flex; align-items: center; gap: 10px; margin-bottom: 20px; padding-bottom: 15px; border-bottom: 1px solid #eee; } .back-to-methods { background: none; border: none; font-size: 20px; cursor: pointer; color: #6a11cb; padding: 5px; border-radius: 4px; transition: background 0.2s; } .back-to-methods:hover { background: #f0f0f0; } .chat-messages { height: 300px; overflow-y: auto; margin-bottom: 15px; padding: 10px; background: #f9f9f9; border-radius: 8px; } .chat-input-area { display: flex; flex-direction: column; gap: 10px; } .chat-input-area textarea { width: 100%; padding: 12px; border: 1px solid #ddd; border-radius: 8px; resize: none; font-family: inherit; font-size: 14px; } .send-message { background: #4a6ee0; color: white; border: none; padding: 10px 20px; border-radius: 8px; cursor: pointer; font-weight: 600; transition: background 0.3s; align-self: flex-end; } .send-message:hover { background: #3a5ed0; } /* 反馈表单样式 */ .form-group { margin-bottom: 15px; } .form-group label { display: block; margin-bottom: 5px; font-weight: 600; color: #333; font-size: 14px; } .form-group input, .form-group textarea { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 6px; font-size: 14px; font-family: inherit; } .form-group input:focus, .form-group textarea:focus { outline: none; border-color: #4a6ee0; box-shadow: 0 0 0 2px rgba(74, 110, 224, 0.2); } .submit-feedback { background: linear-gradient(135deg, #4a6ee0 0%, #6a11cb 100%); color: white; border: none; padding: 12px 30px; border-radius: 8px; cursor: pointer; font-weight: 600; font-size: 16px; width: 100%; transition: transform 0.2s; } .submit-feedback:hover { transform: translateY(-2px); } /* 响应式设计 */ @media (max-width: 768px) { .floating-contact-container { bottom: 20px; right: 20px; } .floating-contact-panel { width: 300px; right: -10px; } .contact-methods { grid-template-columns: 1fr; } } @media (max-width: 480px) { .floating-contact-panel { width: calc(100vw - 40px); right: -20px; } .floating-contact-main-btn { padding: 12px 16px; } .contact-text { display: none; } }
-
- 继续在floating-contact.js文件中添加以下代码: // 处理电话联系 function handlePhoneCall() { const phoneNumber = '400-123-4567'; if (confirm(`是否要拨打 ${phoneNumber}?`)) { window.location.href = `tel:${phoneNumber}`; } } // 处理邮件联系 function handleEmail() { const email = 'support@example.com'; const subject = encodeURIComponent('网站咨询'); const body = encodeURIComponent('您好,我想咨询以下问题:nn'); window.location.href = `mailto:${email}?subject=${subject}&body=${body}`; } // 处理联系方法点击 methodItems.forEach(item => { item.addEventListener('click', function() { const method = this.dataset.method; switch(method) { case 'chat': showChatInterface(); break; case 'phone': handlePhoneCall(); break; case 'email': handleEmail(); break; case 'form': showFeedbackForm(); break; } }); }); // 返回按钮事件 backButtons.forEach(btn => { btn.addEventListener('click', resetToMethodsView); }); // 发送消息按钮事件 sendMessageBtn.addEventListener('click', sendChatMessage); // 回车发送消息 chatInput.addEventListener('keydown', function(e) { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendChatMessage(); } }); // 主按钮点击事件 mainBtn.addEventListener('click', togglePanel); // 关闭按钮事件 closeBtn.addEventListener('click', togglePanel); // 点击面板外部关闭 document.addEventListener('click', function(e) { if (isPanelOpen && !floatingWidget.contains(e.target) && !e.target.closest('.floating-contact-container')) { togglePanel(); } }); // 反馈表单提交处理 feedbackFormElement.addEventListener('submit', function(e) { e.preventDefault(); // 收集表单数据 const formData = { name: document.getElementById('feedbackName').value, email: document.getElementById('feedbackEmail').value, subject: document.getElementById('feedbackSubject').value, message: document.getElementById('feedbackMessage').value, timestamp: new Date().toISOString(), page: window.location.href }; // 显示加载状态 const submitBtn = this.querySelector('.submit-feedback'); const originalText = submitBtn.textContent; submitBtn.textContent = '提交中...'; submitBtn.disabled = true; // 发送数据到WordPress后台 fetch('/wp-admin/admin-ajax.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: new URLSearchParams({ action: 'submit_feedback', nonce: floatingContactData.nonce, ...formData }) }) .then(response => response.json()) .then(data => { if (data.success) { alert('感谢您的反馈!我们会尽快处理。'); feedbackFormElement.reset(); togglePanel(); } else { alert('提交失败,请稍后重试。'); } }) .catch(error => { console.error('Error:', error); alert('网络错误,请检查连接后重试。'); }) .finally(() => { submitBtn.textContent = originalText; submitBtn.disabled = false; }); }); // 添加聊天消息样式 const style = document.createElement('style'); style.textContent = ` .chat-message { margin-bottom: 15px; padding: 10px 15px; border-radius: 18px; max-width: 80%; position: relative; animation: messageAppear 0.3s ease; } @keyframes messageAppear { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: translateY(0); } } .user-message { background: #4a6ee0; color: white; margin-left: auto; border-bottom-right-radius: 5px; } .system-message { background: #f0f0f0; color: #333; margin-right: auto; border-bottom-left-radius: 5px; } .message-content { word-wrap: break-word; line-height: 1.4; } .message-time { font-size: 11px; opacity: 0.7; margin-top: 5px; text-align: right; } .user-message .message-time { color: rgba(255, 255, 255, 0.8); } .system-message .message-time { color: #666; } `; document.head.appendChild(style); });
- 在子主题的functions.php文件中添加后端处理代码: <?php /** * 浮动联系窗口功能集成 */ // 1. 注册并加载必要的脚本和样式 function floating_contact_enqueue_scripts() { // 加载CSS样式 wp_enqueue_style('floating-contact-style', get_stylesheet_directory_uri() . '/style.css'); // 加载JavaScript wp_enqueue_script('floating-contact-script', get_stylesheet_directory_uri() . '/floating-contact.js', array('jquery'), '1.0.0', true); // 传递数据到JavaScript wp_localize_script('floating-contact-script', 'floatingContactData', array( 'ajax_url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('floating_contact_nonce') )); } add_action('wp_enqueue_scripts', 'floating_contact_enqueue_scripts'); // 2. 在网站中插入浮动联系窗口 function insert_floating_contact_widget() { if (!is_admin()) { echo floating_contact_html(); } } add_action('wp_footer', 'insert_floating_contact_widget'); // 3. 处理反馈表单提交 function handle_feedback_submission() { // 验证nonce if (!wp_verify_nonce($_POST['nonce'], 'floating_contact_nonce')) { wp_die('安全验证失败'); } // 验证必填字段 $required_fields = array('name', 'email', 'message'); foreach ($required_fields as $field) { if (empty($_POST[$field])) { wp_send_json_error('请填写所有必填字段'); } } // 验证邮箱格式 if (!is_email($_POST['email'])) { wp_send_json_error('邮箱格式不正确'); } // 清理输入数据 $name = sanitize_text_field($_POST['name']); $email = sanitize_email($_POST['email']); $subject = sanitize_text_field($_POST['subject']); $message = sanitize_textarea_field($_POST['message']); $page_url = esc_url_raw($_POST['page']); // 创建反馈数据数组 $feedback_data = array( 'post_title' => $subject ?: '来自 ' . $name . ' 的反馈', 'post_content' => $message, 'post_status' => 'pending', // 设置为待审核状态 'post_type' => 'feedback', // 自定义文章类型 'meta_input' => array( 'feedback_email' => $email, 'feedback_page' => $page_url, 'feedback_date' => current_time('mysql') ) ); // 插入到数据库 $post_id = wp_insert_post($feedback_data); if ($post_id && !is_wp_error($post_id)) { // 发送邮件通知管理员 $admin_email = get_option('admin_email'); $mail_subject = '新的网站反馈:' . ($subject ?: '无主题'); $mail_message = " 收到新的网站反馈: 姓名:{$name} 邮箱:{$email} 来源页面:{$page_url} 提交时间:" . date('Y-m-d H:i:s') . " 反馈内容: {$message} 您可以在WordPress后台查看和处理此反馈。 "; wp_mail($admin_email, $mail_subject, $mail_message); wp_send_json_success('反馈提交成功'); } else { wp_send_json_error('提交失败,请稍后重试'); } } add_action('wp_ajax_submit_feedback', 'handle_feedback_submission'); add_action('wp_ajax_nopriv_submit_feedback', 'handle_feedback_submission'); // 4. 创建自定义文章类型存储反馈 function create_feedback_post_type() { register_post_type('feedback', array( 'labels' => array( 'name' => '用户反馈', 'singular_name' => '反馈', 'menu_name' => '用户反馈', 'all_items' => '所有反馈', 'view_item' => '查看反馈', 'add_new_item' => '添加新反馈', 'add_new' => '新反馈', 'edit_item' => '编辑反馈', 'update_item' => '更新反馈', 'search_items' => '搜索反馈', 'not_found' => '未找到', 'not_found_in_trash' => '回收站中未找到' ), 'public' => false, 'show_ui' => true, 'show_in_menu' => true, 'show_in_admin_bar' => true, 'menu_position' => 25, 'menu_icon' => 'dashicons-format-chat', 'capability_type' => 'post', 'hierarchical' => false, 'supports' => array('title', 'editor'), 'has_archive' => false, 'rewrite' => false, 'exclude_from_search' => true, 'publicly_queryable' => false, 'show_in_rest' => false ) ); } add_action('init', 'create_feedback_post_type'); // 5. 添加快捷码支持 function floating_contact_shortcode($atts) { $atts = shortcode_atts(array( 'position' => 'right', 'color' => '#4a6ee0' ), $atts); // 这里可以添加根据短码参数自定义样式的逻辑 return floating_contact_html(); } add_shortcode('floating_contact', 'floating_contact_shortcode'); ?>
-
- 在functions.php中添加以下代码来增强反馈管理功能: <?php /** * 反馈管理功能增强 */ // 1. 添加自定义管理列 function add_feedback_columns($columns) { $new_columns = array( 'cb' => $columns['cb'], 'title' => '主题', 'feedback_email' => '邮箱', 'feedback_page' => '来源页面', 'feedback_date' => '提交时间', 'feedback_status' => '状态' ); return $new_columns; } add_filter('manage_feedback_posts_columns', 'add_feedback_columns'); // 2. 填充自定义列内容 function custom_feedback_column($column, $post_id) { switch ($column) { case 'feedback_email': echo get_post_meta($post_id, 'feedback_email', true); break; case 'feedback_page': $page_url = get_post_meta($post_id, 'feedback_page', true); echo '<a href="' . esc_url($page_url) . '" target="_blank">查看页面</a>'; break; case 'feedback_date': echo get_post_meta($post_id, 'feedback_date', true); break; case 'feedback_status': $status = get_post_status($post_id); $status_labels = array( 'publish' => '已处理', 'pending' => '待处理', 'draft' => '草稿' ); echo isset($status_labels[$status]) ? $status_labels[$status] : $status; break; } } add_action('manage_feedback_posts_custom_column', 'custom_feedback_column', 10, 2); // 3. 添加快速操作 function feedback_quick_actions($actions, $post) { if ($post->post_type == 'feedback') { // 添加"标记为已处理"操作 if ($post->post_status == 'pending') { $actions['process'] = sprintf( '<a href="%s" style="color:#46b450;">标记为已处理</a>', wp_nonce_url(admin_url("admin-ajax.php?action=process_feedback&post_id=$post->ID"), 'process_feedback') ); } // 添加"发送回复"操作 $email = get_post_meta($post->ID, 'feedback_email', true); if ($email) { $actions['reply'] = sprintf( '<a href="mailto:%s?subject=回复您的反馈">发送邮件回复</a>', esc_attr($email) ); } } return $actions; } add_filter('post_row_actions', 'feedback_quick_actions', 10, 2); // 4. 处理快速操作请求 function process_feedback_ajax() { if (!isset($_GET['post_id']) || !wp_verify_nonce($_GET['_wpnonce'], 'process_feedback')) { wp_die('安全验证失败'); } $post_id = intval($_GET['post_id']); $updated = wp_update_post(array( 'ID' => $post_id, 'post_status' => 'publish' )); if ($updated) { wp_redirect(admin_url('edit.php?post_type=feedback&processed=1')); exit; } else { wp_die('处理失败'); } } add_action('wp_ajax_process_feedback', 'process_feedback_ajax'); // 5. 添加反馈统计仪表板小工具 function add_feedback_dashboard_widget() { wp_add_dashboard_widget( 'feedback_stats_widget', '用户反馈统计', 'display_feedback_stats' ); } add_action('wp_dashboard_setup', 'add_feedback_dashboard_widget'); function display_feedback_stats() { global $wpdb; // 获取统计数据 $total = wp_count_posts('feedback')->publish + wp_count_posts('feedback')->pending; $pending = wp_count_posts('feedback')->pending; $processed = wp_count_posts('feedback')->publish; // 最近7天反馈数量 $recent_feedback = $wpdb->get_var($wpdb->prepare( "SELECT COUNT(*) FROM {$wpdb->posts} WHERE post_type = 'feedback' AND post_date >= %s", date('Y-m-d', strtotime('-7 days')) )); echo '<div class="feedback-stats">'; echo '<p><strong>总反馈数:</strong>' . $total . '</p>'; echo '<p><strong>待处理:</strong>' . $pending . '</p>'; echo '<p><strong>已处理:</strong>' . $processed . '</p>'; echo '<p><strong>最近7天:</strong>' . $recent_feedback . '</p>'; echo '</div>'; // 如果有待处理反馈,显示链接 if ($pending > 0) { echo '<p><a href="' . admin_url('edit.php?post_type=feedback&post_status=pending') . '" class="button button-primary">查看待处理反馈</a></p>'; } } ?>
- 创建新的JavaScript文件chat-enhanced.js: /** * 增强版实时聊天功能 */ class EnhancedChat { constructor() { this.socket = null; this.userId = this.generateUserId(); this.sessionId = this.generateSessionId(); this.isConnected = false; this.typingTimeout = null; this.init(); } generateUserId() { let userId = localStorage.getItem('chat_user_id'); if (!userId) { userId = 'user_' + Math.random().toString(36).substr(2, 9); localStorage.setItem('chat_user_id', userId); } return userId; } generateSessionId() { return 'session_' + Date.now(); } init() { this.connectWebSocket(); this.setupEventListeners(); this.loadChatHistory(); } connectWebSocket() { // 这里应该使用您的WebSocket服务器地址 const wsUrl = 'wss://your-websocket-server.com/chat'; try { this.socket = new WebSocket(wsUrl); this.socket.onopen = () => { this.isConnected = true; this.sendSystemMessage('已连接到客服系统'); this.registerUser(); }; this.socket.onmessage = (event) => { const data = JSON.parse(event.data); this.handleIncomingMessage(data); }; this.socket.onclose = () => { this.isConnected = false; this.sendSystemMessage('连接已断开,正在尝试重连...'); setTimeout(() => this.connectWebSocket(), 5000); }; this.socket.onerror = (error) => { console.error('WebSocket错误:', error); }; } catch (error) { console.error('连接失败:', error); this.fallbackToAJAX(); } } fallbackToAJAX() {
在当今互联网时代,用户体验已成为网站成功的关键因素之一。根据研究,网站访问者平均只花费15秒决定是否继续浏览一个网站。在这短暂的时间内,能否快速找到联系方式和反馈渠道直接影响着转化率和用户满意度。
浮动在线联系与反馈窗口作为一种常见的互联网小工具,具有以下优势:
- 即时可访问性:无论用户滚动到页面哪个位置,联系入口始终可见
- 提升转化率:减少用户寻找联系方式的步骤,提高咨询可能性
- 增强用户体验:提供便捷的反馈渠道,收集用户意见
- 专业形象展示:展示企业的在线服务能力和响应速度
本文将详细指导您如何通过WordPress代码二次开发,实现一个功能完善、美观实用的浮动在线联系与反馈窗口。
在开始之前,请确保您的WordPress环境满足以下要求:
- WordPress版本:5.0或更高
- PHP版本:7.2或更高(推荐7.4+)
- 基本的HTML、CSS、JavaScript知识
- 代码编辑器(如VS Code、Sublime Text等)
- FTP客户端或WordPress文件管理器访问权限
为了避免主题更新导致自定义代码丢失,我们强烈建议使用子主题进行开发:
- 在WordPress的
wp-content/themes/目录下创建新文件夹,命名为yourtheme-child(将"yourtheme"替换为您的主题名称) -
在子主题文件夹中创建
style.css文件,添加以下内容:/* Theme Name: YourTheme Child Theme URI: https://example.com/ Description: Child theme for adding floating contact widget Author: Your Name Author URI: https://example.com/ Template: yourtheme Version: 1.0.0 */ -
创建
functions.php文件,添加以下代码启用子主题:<?php add_action('wp_enqueue_scripts', 'my_child_theme_enqueue_styles'); function my_child_theme_enqueue_styles() { wp_enqueue_style('parent-style', get_template_directory_uri() . '/style.css'); wp_enqueue_style('child-style', get_stylesheet_directory_uri() . '/style.css', array('parent-style')); } ?> - 在WordPress后台"外观"→"主题"中激活您的子主题
在子主题文件夹中创建floating-contact.php文件,添加以下HTML结构:
<?php
/**
* Floating Contact Widget HTML Structure
*/
function floating_contact_html() {
ob_start();
?>
<!-- 浮动联系窗口主容器 -->
<div id="floating-contact-widget" class="floating-contact-container">
<!-- 主按钮 -->
<div class="floating-contact-main-btn">
<span class="contact-icon">💬</span>
<span class="contact-text">联系我们</span>
</div>
<!-- 展开面板 -->
<div class="floating-contact-panel">
<div class="panel-header">
<h3>在线联系</h3>
<button class="close-panel">×</button>
</div>
<div class="panel-content">
<!-- 联系渠道选择 -->
<div class="contact-methods">
<div class="method-item" data-method="chat">
<div class="method-icon">💬</div>
<div class="method-info">
<h4>在线聊天</h4>
<p>即时响应,快速解答</p>
</div>
</div>
<div class="method-item" data-method="phone">
<div class="method-icon">📞</div>
<div class="method-info">
<h4>电话联系</h4>
<p>400-123-4567</p>
</div>
</div>
<div class="method-item" data-method="email">
<div class="method-icon">✉️</div>
<div class="method-info">
<h4>邮件反馈</h4>
<p>24小时内回复</p>
</div>
</div>
<div class="method-item" data-method="form">
<div class="method-icon">📝</div>
<div class="method-info">
<h4>提交表单</h4>
<p>详细问题反馈</p>
</div>
</div>
</div>
<!-- 聊天界面 -->
<div class="chat-interface" style="display:none;">
<div class="chat-header">
<button class="back-to-methods">←</button>
<h4>在线客服</h4>
</div>
<div class="chat-messages">
<!-- 聊天消息将通过JavaScript动态加载 -->
</div>
<div class="chat-input-area">
<textarea placeholder="请输入您的问题..." rows="3"></textarea>
<button class="send-message">发送</button>
</div>
</div>
<!-- 反馈表单 -->
<div class="feedback-form" style="display:none;">
<div class="form-header">
<button class="back-to-methods">←</button>
<h4>问题反馈</h4>
</div>
<form id="feedbackForm">
<div class="form-group">
<label for="feedbackName">姓名 *</label>
<input type="text" id="feedbackName" name="name" required>
</div>
<div class="form-group">
<label for="feedbackEmail">邮箱 *</label>
<input type="email" id="feedbackEmail" name="email" required>
</div>
<div class="form-group">
<label for="feedbackSubject">主题</label>
<input type="text" id="feedbackSubject" name="subject">
</div>
<div class="form-group">
<label for="feedbackMessage">内容 *</label>
<textarea id="feedbackMessage" name="message" rows="5" required></textarea>
</div>
<div class="form-group">
<button type="submit" class="submit-feedback">提交反馈</button>
</div>
</form>
</div>
</div>
</div>
</div>
<?php
return ob_get_clean();
}
?>
在子主题的style.css文件中添加以下样式:
/* 浮动联系窗口基础样式 */
.floating-contact-container {
position: fixed;
bottom: 30px;
right: 30px;
z-index: 9999;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
}
/* 主按钮样式 */
.floating-contact-main-btn {
background: linear-gradient(135deg, #4a6ee0 0%, #6a11cb 100%);
color: white;
padding: 15px 20px;
border-radius: 50px;
cursor: pointer;
display: flex;
align-items: center;
gap: 10px;
box-shadow: 0 5px 15px rgba(106, 17, 203, 0.3);
transition: all 0.3s ease;
user-select: none;
}
.floating-contact-main-btn:hover {
transform: translateY(-3px);
box-shadow: 0 8px 20px rgba(106, 17, 203, 0.4);
}
.contact-icon {
font-size: 20px;
}
.contact-text {
font-weight: 600;
font-size: 16px;
}
/* 展开面板样式 */
.floating-contact-panel {
position: absolute;
bottom: 70px;
right: 0;
width: 350px;
background: white;
border-radius: 12px;
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
overflow: hidden;
display: none;
animation: slideUp 0.3s ease;
}
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.panel-header {
background: linear-gradient(135deg, #4a6ee0 0%, #6a11cb 100%);
color: white;
padding: 15px 20px;
display: flex;
justify-content: space-between;
align-items: center;
}
.panel-header h3 {
margin: 0;
font-size: 18px;
}
.close-panel {
background: none;
border: none;
color: white;
font-size: 24px;
cursor: pointer;
line-height: 1;
padding: 0;
width: 30px;
height: 30px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 50%;
transition: background 0.2s;
}
.close-panel:hover {
background: rgba(255, 255, 255, 0.2);
}
.panel-content {
padding: 20px;
}
/* 联系方法样式 */
.contact-methods {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 15px;
}
.method-item {
background: #f8f9fa;
border-radius: 8px;
padding: 15px;
cursor: pointer;
transition: all 0.2s ease;
border: 1px solid #e9ecef;
}
.method-item:hover {
background: #e9ecef;
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.method-icon {
font-size: 24px;
margin-bottom: 8px;
}
.method-info h4 {
margin: 0 0 5px 0;
font-size: 14px;
color: #333;
}
.method-info p {
margin: 0;
font-size: 12px;
color: #666;
}
/* 聊天界面样式 */
.chat-interface,
.feedback-form {
animation: fadeIn 0.3s ease;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.chat-header,
.form-header {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 20px;
padding-bottom: 15px;
border-bottom: 1px solid #eee;
}
.back-to-methods {
background: none;
border: none;
font-size: 20px;
cursor: pointer;
color: #6a11cb;
padding: 5px;
border-radius: 4px;
transition: background 0.2s;
}
.back-to-methods:hover {
background: #f0f0f0;
}
.chat-messages {
height: 300px;
overflow-y: auto;
margin-bottom: 15px;
padding: 10px;
background: #f9f9f9;
border-radius: 8px;
}
.chat-input-area {
display: flex;
flex-direction: column;
gap: 10px;
}
.chat-input-area textarea {
width: 100%;
padding: 12px;
border: 1px solid #ddd;
border-radius: 8px;
resize: none;
font-family: inherit;
font-size: 14px;
}
.send-message {
background: #4a6ee0;
color: white;
border: none;
padding: 10px 20px;
border-radius: 8px;
cursor: pointer;
font-weight: 600;
transition: background 0.3s;
align-self: flex-end;
}
.send-message:hover {
background: #3a5ed0;
}
/* 反馈表单样式 */
.form-group {
margin-bottom: 15px;
}
.form-group label {
display: block;
margin-bottom: 5px;
font-weight: 600;
color: #333;
font-size: 14px;
}
.form-group input,
.form-group textarea {
width: 100%;
padding: 10px;
border: 1px solid #ddd;
border-radius: 6px;
font-size: 14px;
font-family: inherit;
}
.form-group input:focus,
.form-group textarea:focus {
outline: none;
border-color: #4a6ee0;
box-shadow: 0 0 0 2px rgba(74, 110, 224, 0.2);
}
.submit-feedback {
background: linear-gradient(135deg, #4a6ee0 0%, #6a11cb 100%);
color: white;
border: none;
padding: 12px 30px;
border-radius: 8px;
cursor: pointer;
font-weight: 600;
font-size: 16px;
width: 100%;
transition: transform 0.2s;
}
.submit-feedback:hover {
transform: translateY(-2px);
}
/* 响应式设计 */
@media (max-width: 768px) {
.floating-contact-container {
bottom: 20px;
right: 20px;
}
.floating-contact-panel {
width: 300px;
right: -10px;
}
.contact-methods {
grid-template-columns: 1fr;
}
}
@media (max-width: 480px) {
.floating-contact-panel {
width: calc(100vw - 40px);
right: -20px;
}
.floating-contact-main-btn {
padding: 12px 16px;
}
.contact-text {
display: none;
}
}
在子主题文件夹中创建floating-contact.js文件:
/**
* 浮动联系窗口交互功能
*/
document.addEventListener('DOMContentLoaded', function() {
// 获取DOM元素
const floatingWidget = document.getElementById('floating-contact-widget');
const mainBtn = floatingWidget.querySelector('.floating-contact-main-btn');
const contactPanel = floatingWidget.querySelector('.floating-contact-panel');
const closeBtn = floatingWidget.querySelector('.close-panel');
const methodItems = floatingWidget.querySelectorAll('.method-item');
const backButtons = floatingWidget.querySelectorAll('.back-to-methods');
const chatInterface = floatingWidget.querySelector('.chat-interface');
const feedbackForm = floatingWidget.querySelector('.feedback-form');
const contactMethods = floatingWidget.querySelector('.contact-methods');
const sendMessageBtn = floatingWidget.querySelector('.send-message');
const chatInput = floatingWidget.querySelector('.chat-input-area textarea');
const chatMessages = floatingWidget.querySelector('.chat-messages');
const feedbackFormElement = document.getElementById('feedbackForm');
// 初始状态
let isPanelOpen = false;
let currentView = 'methods'; // methods, chat, form
// 切换面板显示/隐藏
function togglePanel() {
isPanelOpen = !isPanelOpen;
if (isPanelOpen) {
contactPanel.style.display = 'block';
mainBtn.style.transform = 'rotate(45deg)';
} else {
contactPanel.style.display = 'none';
mainBtn.style.transform = 'rotate(0deg)';
resetToMethodsView();
}
}
// 重置到联系方法视图
function resetToMethodsView() {
currentView = 'methods';
contactMethods.style.display = 'grid';
chatInterface.style.display = 'none';
feedbackForm.style.display = 'none';
}
// 切换到聊天界面
function showChatInterface() {
currentView = 'chat';
contactMethods.style.display = 'none';
chatInterface.style.display = 'block';
feedbackForm.style.display = 'none';
chatInput.focus();
// 添加欢迎消息
if (!chatMessages.querySelector('.welcome-message')) {
addChatMessage('system', '您好!我是在线客服,有什么可以帮您的吗?', 'welcome-message');
}
}
// 切换到反馈表单
function showFeedbackForm() {
currentView = 'form';
contactMethods.style.display = 'none';
chatInterface.style.display = 'none';
feedbackForm.style.display = 'block';
}
// 添加聊天消息
function addChatMessage(type, content, className = '') {
const messageDiv = document.createElement('div');
messageDiv.className = `chat-message ${type}-message ${className}`;
const timestamp = new Date().toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
messageDiv.innerHTML = `
<div class="message-content">${content}</div>
<div class="message-time">${timestamp}</div>
`;
chatMessages.appendChild(messageDiv);
chatMessages.scrollTop = chatMessages.scrollHeight;
}
// 发送聊天消息
function sendChatMessage() {
const message = chatInput.value.trim();
if (!message) return;
// 添加用户消息
addChatMessage('user', message);
chatInput.value = '';
// 模拟客服回复(实际应用中应通过AJAX发送到服务器)
setTimeout(() => {
const responses = [
'感谢您的提问,我会尽快为您解答。',
'我明白了,请您稍等,我正在查询相关信息。',
'这是一个很好的问题,我们的专家会尽快回复您。',
'我已经记录下您的问题,稍后会有专人联系您。'
];
const randomResponse = responses[Math.floor(Math.random() * responses.length)];
addChatMessage('system', randomResponse);
继续在floating-contact.js文件中添加以下代码:
// 处理电话联系
function handlePhoneCall() {
const phoneNumber = '400-123-4567';
if (confirm(`是否要拨打 ${phoneNumber}?`)) {
window.location.href = `tel:${phoneNumber}`;
}
}
// 处理邮件联系
function handleEmail() {
const email = 'support@example.com';
const subject = encodeURIComponent('网站咨询');
const body = encodeURIComponent('您好,我想咨询以下问题:nn');
window.location.href = `mailto:${email}?subject=${subject}&body=${body}`;
}
// 处理联系方法点击
methodItems.forEach(item => {
item.addEventListener('click', function() {
const method = this.dataset.method;
switch(method) {
case 'chat':
showChatInterface();
break;
case 'phone':
handlePhoneCall();
break;
case 'email':
handleEmail();
break;
case 'form':
showFeedbackForm();
break;
}
});
});
// 返回按钮事件
backButtons.forEach(btn => {
btn.addEventListener('click', resetToMethodsView);
});
// 发送消息按钮事件
sendMessageBtn.addEventListener('click', sendChatMessage);
// 回车发送消息
chatInput.addEventListener('keydown', function(e) {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendChatMessage();
}
});
// 主按钮点击事件
mainBtn.addEventListener('click', togglePanel);
// 关闭按钮事件
closeBtn.addEventListener('click', togglePanel);
// 点击面板外部关闭
document.addEventListener('click', function(e) {
if (isPanelOpen &&
!floatingWidget.contains(e.target) &&
!e.target.closest('.floating-contact-container')) {
togglePanel();
}
});
// 反馈表单提交处理
feedbackFormElement.addEventListener('submit', function(e) {
e.preventDefault();
// 收集表单数据
const formData = {
name: document.getElementById('feedbackName').value,
email: document.getElementById('feedbackEmail').value,
subject: document.getElementById('feedbackSubject').value,
message: document.getElementById('feedbackMessage').value,
timestamp: new Date().toISOString(),
page: window.location.href
};
// 显示加载状态
const submitBtn = this.querySelector('.submit-feedback');
const originalText = submitBtn.textContent;
submitBtn.textContent = '提交中...';
submitBtn.disabled = true;
// 发送数据到WordPress后台
fetch('/wp-admin/admin-ajax.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
action: 'submit_feedback',
nonce: floatingContactData.nonce,
...formData
})
})
.then(response => response.json())
.then(data => {
if (data.success) {
alert('感谢您的反馈!我们会尽快处理。');
feedbackFormElement.reset();
togglePanel();
} else {
alert('提交失败,请稍后重试。');
}
})
.catch(error => {
console.error('Error:', error);
alert('网络错误,请检查连接后重试。');
})
.finally(() => {
submitBtn.textContent = originalText;
submitBtn.disabled = false;
});
});
// 添加聊天消息样式
const style = document.createElement('style');
style.textContent = `
.chat-message {
margin-bottom: 15px;
padding: 10px 15px;
border-radius: 18px;
max-width: 80%;
position: relative;
animation: messageAppear 0.3s ease;
}
@keyframes messageAppear {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.user-message {
background: #4a6ee0;
color: white;
margin-left: auto;
border-bottom-right-radius: 5px;
}
.system-message {
background: #f0f0f0;
color: #333;
margin-right: auto;
border-bottom-left-radius: 5px;
}
.message-content {
word-wrap: break-word;
line-height: 1.4;
}
.message-time {
font-size: 11px;
opacity: 0.7;
margin-top: 5px;
text-align: right;
}
.user-message .message-time {
color: rgba(255, 255, 255, 0.8);
}
.system-message .message-time {
color: #666;
}
`;
document.head.appendChild(style);
});
在子主题的functions.php文件中添加后端处理代码:
<?php
/**
* 浮动联系窗口功能集成
*/
// 1. 注册并加载必要的脚本和样式
function floating_contact_enqueue_scripts() {
// 加载CSS样式
wp_enqueue_style('floating-contact-style', get_stylesheet_directory_uri() . '/style.css');
// 加载JavaScript
wp_enqueue_script('floating-contact-script', get_stylesheet_directory_uri() . '/floating-contact.js',
array('jquery'), '1.0.0', true);
// 传递数据到JavaScript
wp_localize_script('floating-contact-script', 'floatingContactData', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('floating_contact_nonce')
));
}
add_action('wp_enqueue_scripts', 'floating_contact_enqueue_scripts');
// 2. 在网站中插入浮动联系窗口
function insert_floating_contact_widget() {
if (!is_admin()) {
echo floating_contact_html();
}
}
add_action('wp_footer', 'insert_floating_contact_widget');
// 3. 处理反馈表单提交
function handle_feedback_submission() {
// 验证nonce
if (!wp_verify_nonce($_POST['nonce'], 'floating_contact_nonce')) {
wp_die('安全验证失败');
}
// 验证必填字段
$required_fields = array('name', 'email', 'message');
foreach ($required_fields as $field) {
if (empty($_POST[$field])) {
wp_send_json_error('请填写所有必填字段');
}
}
// 验证邮箱格式
if (!is_email($_POST['email'])) {
wp_send_json_error('邮箱格式不正确');
}
// 清理输入数据
$name = sanitize_text_field($_POST['name']);
$email = sanitize_email($_POST['email']);
$subject = sanitize_text_field($_POST['subject']);
$message = sanitize_textarea_field($_POST['message']);
$page_url = esc_url_raw($_POST['page']);
// 创建反馈数据数组
$feedback_data = array(
'post_title' => $subject ?: '来自 ' . $name . ' 的反馈',
'post_content' => $message,
'post_status' => 'pending', // 设置为待审核状态
'post_type' => 'feedback', // 自定义文章类型
'meta_input' => array(
'feedback_email' => $email,
'feedback_page' => $page_url,
'feedback_date' => current_time('mysql')
)
);
// 插入到数据库
$post_id = wp_insert_post($feedback_data);
if ($post_id && !is_wp_error($post_id)) {
// 发送邮件通知管理员
$admin_email = get_option('admin_email');
$mail_subject = '新的网站反馈:' . ($subject ?: '无主题');
$mail_message = "
收到新的网站反馈:
姓名:{$name}
邮箱:{$email}
来源页面:{$page_url}
提交时间:" . date('Y-m-d H:i:s') . "
反馈内容:
{$message}
您可以在WordPress后台查看和处理此反馈。
";
wp_mail($admin_email, $mail_subject, $mail_message);
wp_send_json_success('反馈提交成功');
} else {
wp_send_json_error('提交失败,请稍后重试');
}
}
add_action('wp_ajax_submit_feedback', 'handle_feedback_submission');
add_action('wp_ajax_nopriv_submit_feedback', 'handle_feedback_submission');
// 4. 创建自定义文章类型存储反馈
function create_feedback_post_type() {
register_post_type('feedback',
array(
'labels' => array(
'name' => '用户反馈',
'singular_name' => '反馈',
'menu_name' => '用户反馈',
'all_items' => '所有反馈',
'view_item' => '查看反馈',
'add_new_item' => '添加新反馈',
'add_new' => '新反馈',
'edit_item' => '编辑反馈',
'update_item' => '更新反馈',
'search_items' => '搜索反馈',
'not_found' => '未找到',
'not_found_in_trash' => '回收站中未找到'
),
'public' => false,
'show_ui' => true,
'show_in_menu' => true,
'show_in_admin_bar' => true,
'menu_position' => 25,
'menu_icon' => 'dashicons-format-chat',
'capability_type' => 'post',
'hierarchical' => false,
'supports' => array('title', 'editor'),
'has_archive' => false,
'rewrite' => false,
'exclude_from_search' => true,
'publicly_queryable' => false,
'show_in_rest' => false
)
);
}
add_action('init', 'create_feedback_post_type');
// 5. 添加快捷码支持
function floating_contact_shortcode($atts) {
$atts = shortcode_atts(array(
'position' => 'right',
'color' => '#4a6ee0'
), $atts);
// 这里可以添加根据短码参数自定义样式的逻辑
return floating_contact_html();
}
add_shortcode('floating_contact', 'floating_contact_shortcode');
?>
在functions.php中添加以下代码来增强反馈管理功能:
<?php
/**
* 反馈管理功能增强
*/
// 1. 添加自定义管理列
function add_feedback_columns($columns) {
$new_columns = array(
'cb' => $columns['cb'],
'title' => '主题',
'feedback_email' => '邮箱',
'feedback_page' => '来源页面',
'feedback_date' => '提交时间',
'feedback_status' => '状态'
);
return $new_columns;
}
add_filter('manage_feedback_posts_columns', 'add_feedback_columns');
// 2. 填充自定义列内容
function custom_feedback_column($column, $post_id) {
switch ($column) {
case 'feedback_email':
echo get_post_meta($post_id, 'feedback_email', true);
break;
case 'feedback_page':
$page_url = get_post_meta($post_id, 'feedback_page', true);
echo '<a href="' . esc_url($page_url) . '" target="_blank">查看页面</a>';
break;
case 'feedback_date':
echo get_post_meta($post_id, 'feedback_date', true);
break;
case 'feedback_status':
$status = get_post_status($post_id);
$status_labels = array(
'publish' => '已处理',
'pending' => '待处理',
'draft' => '草稿'
);
echo isset($status_labels[$status]) ? $status_labels[$status] : $status;
break;
}
}
add_action('manage_feedback_posts_custom_column', 'custom_feedback_column', 10, 2);
// 3. 添加快速操作
function feedback_quick_actions($actions, $post) {
if ($post->post_type == 'feedback') {
// 添加"标记为已处理"操作
if ($post->post_status == 'pending') {
$actions['process'] = sprintf(
'<a href="%s" style="color:#46b450;">标记为已处理</a>',
wp_nonce_url(admin_url("admin-ajax.php?action=process_feedback&post_id=$post->ID"), 'process_feedback')
);
}
// 添加"发送回复"操作
$email = get_post_meta($post->ID, 'feedback_email', true);
if ($email) {
$actions['reply'] = sprintf(
'<a href="mailto:%s?subject=回复您的反馈">发送邮件回复</a>',
esc_attr($email)
);
}
}
return $actions;
}
add_filter('post_row_actions', 'feedback_quick_actions', 10, 2);
// 4. 处理快速操作请求
function process_feedback_ajax() {
if (!isset($_GET['post_id']) || !wp_verify_nonce($_GET['_wpnonce'], 'process_feedback')) {
wp_die('安全验证失败');
}
$post_id = intval($_GET['post_id']);
$updated = wp_update_post(array(
'ID' => $post_id,
'post_status' => 'publish'
));
if ($updated) {
wp_redirect(admin_url('edit.php?post_type=feedback&processed=1'));
exit;
} else {
wp_die('处理失败');
}
}
add_action('wp_ajax_process_feedback', 'process_feedback_ajax');
// 5. 添加反馈统计仪表板小工具
function add_feedback_dashboard_widget() {
wp_add_dashboard_widget(
'feedback_stats_widget',
'用户反馈统计',
'display_feedback_stats'
);
}
add_action('wp_dashboard_setup', 'add_feedback_dashboard_widget');
function display_feedback_stats() {
global $wpdb;
// 获取统计数据
$total = wp_count_posts('feedback')->publish + wp_count_posts('feedback')->pending;
$pending = wp_count_posts('feedback')->pending;
$processed = wp_count_posts('feedback')->publish;
// 最近7天反馈数量
$recent_feedback = $wpdb->get_var($wpdb->prepare(
"SELECT COUNT(*) FROM {$wpdb->posts}
WHERE post_type = 'feedback'
AND post_date >= %s",
date('Y-m-d', strtotime('-7 days'))
));
echo '<div class="feedback-stats">';
echo '<p><strong>总反馈数:</strong>' . $total . '</p>';
echo '<p><strong>待处理:</strong>' . $pending . '</p>';
echo '<p><strong>已处理:</strong>' . $processed . '</p>';
echo '<p><strong>最近7天:</strong>' . $recent_feedback . '</p>';
echo '</div>';
// 如果有待处理反馈,显示链接
if ($pending > 0) {
echo '<p><a href="' . admin_url('edit.php?post_type=feedback&post_status=pending') .
'" class="button button-primary">查看待处理反馈</a></p>';
}
}
?>
创建新的JavaScript文件chat-enhanced.js:
/**
* 增强版实时聊天功能
*/
class EnhancedChat {
constructor() {
this.socket = null;
this.userId = this.generateUserId();
this.sessionId = this.generateSessionId();
this.isConnected = false;
this.typingTimeout = null;
this.init();
}
generateUserId() {
let userId = localStorage.getItem('chat_user_id');
if (!userId) {
userId = 'user_' + Math.random().toString(36).substr(2, 9);
localStorage.setItem('chat_user_id', userId);
}
return userId;
}
generateSessionId() {
return 'session_' + Date.now();
}
init() {
this.connectWebSocket();
this.setupEventListeners();
this.loadChatHistory();
}
connectWebSocket() {
// 这里应该使用您的WebSocket服务器地址
const wsUrl = 'wss://your-websocket-server.com/chat';
try {
this.socket = new WebSocket(wsUrl);
this.socket.onopen = () => {
this.isConnected = true;
this.sendSystemMessage('已连接到客服系统');
this.registerUser();
};
this.socket.onmessage = (event) => {
const data = JSON.parse(event.data);
this.handleIncomingMessage(data);
};
this.socket.onclose = () => {
this.isConnected = false;
this.sendSystemMessage('连接已断开,正在尝试重连...');
setTimeout(() => this.connectWebSocket(), 5000);
};
this.socket.onerror = (error) => {
console.error('WebSocket错误:', error);
};
} catch (error) {
console.error('连接失败:', error);
this.fallbackToAJAX();
}
}
fallbackToAJAX() {


