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

如何在刷新本地页面时保存可创建、可移动的div?

解决方案:用localStorage持久化可拖动笔记状态

核心思路是通过localStorage存储每个笔记元素的关键状态(ID、位置、内容等),页面加载时读取存储数据渲染元素,每次创建或拖动笔记后实时更新存储,确保刷新后状态保留。

先修正原代码的小问题

  • 变量名拼写错误:iscklick → isclick
  • 重复绑定事件:每次mousedown都绑定新的mousemove/mouseup事件,会导致多次触发,改为只绑定一次全局事件,通过当前激活的元素ID来控制拖动。

完整修改后的代码

HTML

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Demo</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <style>
        html, body{
            background-color:lightgray;
            margin:0;
            height:100%;
            width:100%;
        }
        .add {
            position: relative;
            float:left;
            background-color: rgb(105, 230, 188);
            color: white;
            border: none;
            height: 50px;
            width: 50px;
            font-size: 43px;
            font-weight: bolder;
            box-shadow: 0 2px 4px darkslategray;
            cursor: pointer;
            border-radius: 70%;
            transition: all 0.2s ease;
            top:45%;
            margin: 2%;
        }
        .add:active{
            background-color: rgb(45, 138, 107);
            box-shadow: 0 0 2px darkslategray;
            transform: translateY(2px);
        }
        .element{
            position:absolute;
            padding: 5px;
            height: 100px;
            width: 200px;
            background-color: yellow;
            box-shadow: 0 2px 4px rgb(172, 172, 106);
            margin: 1%;
            border-radius: 10px;
            float:left;
            overflow: auto;
        }
        .element:hover{
            z-index: 1;
        }
    </style>
</head>
<body>
    <button class='add'>+</button>
    <div class="container"></div>
    <script src="main.js"></script>
</body>
</html>

JavaScript(main.js)

// 存储键名
const STORAGE_KEY = 'noteElements';
let activeElementId = null;

// 保存所有笔记状态到localStorage
function saveNotes() {
    const notes = [];
    $('.element').each(function() {
        const $el = $(this);
        notes.push({
            id: $el.attr('id'),
            top: $el.css('top'),
            left: $el.css('left'),
            content: $el.html() // 后续扩展内容编辑时用
        });
    });
    localStorage.setItem(STORAGE_KEY, JSON.stringify(notes));
}

// 从localStorage加载笔记并渲染
function loadNotes() {
    const savedNotes = localStorage.getItem(STORAGE_KEY);
    if (!savedNotes) {
        // 没有存储数据时创建默认第一个笔记
        createNote('div_1', '50px', '50px', '');
        return;
    }
    const notes = JSON.parse(savedNotes);
    notes.forEach(note => {
        createNote(note.id, note.top, note.left, note.content);
    });
}

// 创建单个笔记元素
function createNote(id, top, left, content) {
    const $note = $(`<div class='element' id='${id}'>${content}</div>`);
    $note.css({ top, left });
    $('.container').append($note);
}

$(document).ready(function() {
    // 页面加载时渲染存储的笔记
    loadNotes();

    // 全局拖动事件(避免重复绑定)
    $(document)
        .on('mousemove', function(event) {
            if (!activeElementId) return;
            const $el = $(`#${activeElementId}`);
            $el.css({
                top: event.pageY - $el.outerHeight() / 2,
                left: event.pageX - $el.outerWidth() / 2
            });
        })
        .on('mouseup', function() {
            if (activeElementId) {
                saveNotes(); // 拖动结束后保存状态
                activeElementId = null;
            }
        });

    // 笔记拖动触发
    $('.container').on('mousedown', '.element', function() {
        activeElementId = this.id;
    });

    // 添加新笔记
    $('.add').click(function() {
        // 生成新ID
        const lastId = $('.element:last').attr('id') || 'div_0';
        const nextIndex = Number(lastId.split('_')[1]) + 1;
        const newId = `div_${nextIndex}`;
        // 默认位置
        createNote(newId, '100px', '100px', '');
        // 保存新状态
        saveNotes();
    });
});

关键逻辑说明

  1. 状态存储:saveNotes函数遍历所有笔记,收集ID、位置、内容(预留扩展),转成JSON字符串存入localStorage。
  2. 状态恢复:loadNotes读取存储的数据,调用createNote渲染每个笔记;如果没有存储数据,创建默认笔记。
  3. 拖动优化:全局绑定一次mousemove和mouseup事件,通过activeElementId控制当前拖动的元素,避免重复绑定导致的性能问题。
  4. 实时保存:创建新笔记、拖动结束时立即调用saveNotes,确保状态实时同步到本地存储。

后续扩展建议

  • 添加笔记内容编辑:给.element绑定blur事件,编辑完成后调用saveNotes保存内容。
  • 添加删除功能:给每个笔记添加删除按钮,点击后移除元素并调用saveNotes更新存储。
  • 支持调整大小:监听resize事件,结束后保存宽高状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 23:19:54