萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JS + CSS 實現無刷新留言板:DOM 動態創建、事件委派、刪除確認、本地存儲持久化

功能特性

  • 輸入內容點擊發布,即時追加到列表頂部/底部。
  • 每條留言帶「刪除」按鈕,點擊彈出確認後移除。
  • 鼠標懸停留明顯示刪除按鈕,移出隱藏。
  • 空內容攔截提示。
  • 可選:localStorage 持久化,刷新不丟失。

核心 HTML/CSS/JS 一體化實現

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>無刷新留言板</title>
<style>
  * { box-sizing: border-box; margin: 0; padding: 0; }
  body { font: 14px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: #f5f5f5; }
  .container { max-width: 600px; margin: 40px auto; background: #fff; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,.1); overflow: hidden; }
  .header { padding: 20px; border-bottom: 1px solid #eee; color: #e74c3c; }
  .list { padding: 0; list-style: none; }
  .msg-item { position: relative; padding: 15px 20px; border-bottom: 1px solid #f0f0f0; transition: background .2s; }
  .msg-item:hover { background: #fafafa; }
  .msg-item:last-child { border-bottom: none; }
  .msg-text { margin-bottom: 8px; word-break: break-word; }
  .msg-meta { font-size: 12px; color: #999; }
  .del-btn { position: absolute; right: 15px; top: 50%; transform: translateY(-50%); background: #e74c3c; color: #fff; border: none; border-radius: 4px; padding: 4px 10px; font-size: 12px; cursor: pointer; opacity: 0; transition: opacity .2s; }
  .msg-item:hover .del-btn { opacity: 1; }
  .input-area { padding: 20px; display: flex; gap: 10px; }
  .input-area textarea { flex: 1; min-height: 80px; padding: 10px; border: 1px solid #ddd; border-radius: 4px; resize: vertical; font: inherit; }
  .input-area button { align-self: flex-start; padding: 10px 20px; background: #3498db; color: #fff; border: none; border-radius: 4px; cursor: pointer; font: inherit; }
  .input-area button:hover { background: #2980b9; }
  .empty-tip { text-align: center; color: #999; padding: 40px 0; }
</style>
</head>
<body>
  <div class="container">
    <h4 class="header">留言板</h4>
    <ul class="list" id="msgList"></ul>
    <div class="input-area">
      <textarea id="msgInput" placeholder="請輸入留言內容..."></textarea>
      <button id="btnPost">發表留言</button>
    </div>
  </div>

  <script>
  (function() {
    var $list = $('#msgList');
    var $input = $('#msgInput');
    var STORAGE_KEY = 'simple_msg_board_v1';

    // 1. 初始化:從 localStorage 恢復
    function init() {
      var data = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]');
      data.forEach(renderMsg);
      updateEmpty();
    }

    // 2. 渲染單條留言
    function renderMsg(item) {
      var $li = $('
  • ' + '
    ' + escapeHtml(item.text) + '
    ' + '
    ' + formatTime(item.time) + '
    ' + '' + '
  • '); $li.find('.del-btn').click(function() { if (confirm('確定刪除這條留言?')) { $li.remove(); removeFromStorage(item.id); updateEmpty(); } }); $list.append($li); } // 3. 發表留言 $('#btnPost').click(function() { var text = $input.val().trim(); if (!text) { alert('請填寫留言內容!'); return; } var item = { id: Date.now(), text: text, time: Date.now() }; renderMsg(item); saveToStorage(item); $input.val('').focus(); }); // 4. 本地存儲 function saveToStorage(item) { var data = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]'); data.unshift(item); // 新增在最前 localStorage.setItem(STORAGE_KEY, JSON.stringify(data)); } function removeFromStorage(id) { var data = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]'); data = data.filter(function(i) { return i.id !== id; }); localStorage.setItem(STORAGE_KEY, JSON.stringify(data)); } // 5. 輔助 function escapeHtml(str) { return str.replace(/[&<>"']/g, function(c) { return {'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]; }); } function formatTime(ts) { var d = new Date(ts); return d.getFullYear()+'-'+(d.getMonth()+1).toString().padStart(2,'0')+'-'+d.getDate().toString().padStart(2,'0') +' '+d.getHours().toString().padStart(2,'0')+':'+d.getMinutes().toString().padStart(2,'0'); } function updateEmpty() { $list.toggleClass('empty', $list.children().length === 0); } // 6. Enter 發送 (Ctrl+Enter 換行) $input.keydown(function(e) { if (e.key === 'Enter' && !e.ctrlKey && !e.shiftKey) { e.preventDefault(); $('#btnPost').click(); } }); init(); })(); </script> <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script> </body> </html>

    關鍵技術點

    1. 事件委派:刪除按鈕動態創建,直接綁定在按鈕上 (jQuery 自動處理),或委派到 $list.on('click', '.del-btn', fn)。
    2. XSS 防護:escapeHtml 轉義用戶輸入,防止腳本注入。
    3. 本地持久化:localStorage 存儲陣列,ID 用 Date.now() 保證唯一。
    4. 無障礙:aria-label、語義化標籤、鍵盤支持 (Enter 發送)。
    5. 動畫體驗:CSS transition 實現懸停顯示刪除按鈕、留言項背景變色。

    擴展方向

    • 分頁/無限滾動加載歷史留言。
    • 回覆/巢狀評論結構。
    • Markdown 渲染、表情包、圖片上傳。
    • WebSocket 實時廣播新留言。
    • 後端 API 替換 localStorage,多用戶共享。
    copyright © 萬盛學電腦網 all rights reserved