You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何保存contenteditable div内容,本地刷新后仍显示?

本地日程规划器内容持久化解决方案

不用数据库的话,直接用浏览器自带的localStorage就能实现——它可以把数据存在用户本地浏览器里,关闭再打开也能读取。下面是完整的代码,JS部分写得简单直白,注释也清晰,你直接复制用就行:

完整代码

HTML

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>本地日程规划器</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <h1>我的日程</h1>
        <!-- 可编辑的日程区域 -->
        <div id="schedule" contenteditable="true" class="schedule-editor"></div>
    </div>
    <script src="script.js"></script>
</body>
</html>

CSS(style.css)

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: Arial, sans-serif;
    background-color: #f0f4f8;
    padding: 20px;
}

.container {
    max-width: 800px;
    margin: 0 auto;
    background-color: white;
    padding: 30px;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

h1 {
    color: #2d3748;
    margin-bottom: 20px;
    text-align: center;
}

.schedule-editor {
    min-height: 400px;
    padding: 20px;
    border: 1px solid #e2e8f0;
    border-radius: 6px;
    font-size: 16px;
    line-height: 1.6;
    background-color: #f7fafc;
}

.schedule-editor:focus {
    outline: none;
    border-color: #4299e1;
    box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.2);
}

JS(script.js)

// 获取可编辑的div元素
const scheduleDiv = document.getElementById('schedule');

// 页面加载时,读取localStorage里保存的内容
window.addEventListener('load', () => {
    const savedContent = localStorage.getItem('scheduleContent');
    if (savedContent) {
        scheduleDiv.innerHTML = savedContent;
    }
});

// 监听输入,每2秒自动保存一次内容(避免频繁存储)
let saveTimer;
scheduleDiv.addEventListener('input', () => {
    // 清除之前的定时器,避免重复触发
    clearTimeout(saveTimer);
    // 延迟2秒保存,减少存储次数
    saveTimer = setTimeout(() => {
        localStorage.setItem('scheduleContent', scheduleDiv.innerHTML);
    }, 2000);
});

关键说明

  • localStorage是浏览器自带的本地存储功能,数据会一直保留在用户浏览器中,除非用户手动清除缓存或删除对应存储项。
  • 设置2秒延迟保存是为了避免每输入一个字符就触发一次存储,减少不必要的性能消耗。
  • 保存的是div的innerHTML,你输入的换行、简单格式都会被完整保留。

内容的提问来源于stack exchange,提问作者junaid ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 02:40:28