当前位置:首页 > JavaScript

js实现编辑

2026-04-06 03:29:31JavaScript

使用 JavaScript 实现编辑功能

基础文本编辑

通过 contenteditable 属性实现简单的文本编辑功能:

<div id="editable" contenteditable="true">点击编辑文本</div>

监听内容变化:

document.getElementById('editable').addEventListener('input', function(e) {
    console.log('新内容:', e.target.innerHTML);
});

表单输入编辑

创建可编辑的表单输入框:

<input type="text" id="textInput" value="可编辑文本">
<button id="saveBtn">保存</button>

处理编辑和保存:

document.getElementById('saveBtn').addEventListener('click', function() {
    const newValue = document.getElementById('textInput').value;
    console.log('保存的内容:', newValue);
});

富文本编辑器实现

使用 document.execCommand 实现基本富文本功能:

<div id="editor" contenteditable="true"></div>
<button onclick="formatText('bold')">加粗</button>
<button onclick="formatText('italic')">斜体</button>

实现格式化函数:

function formatText(command) {
    document.execCommand(command, false, null);
}

使用第三方库

引入 CKEditor 等专业编辑器库:

<script src="https://cdn.ckeditor.com/ckeditor5/36.0.1/classic/ckeditor.js"></script>
<textarea id="editor"></textarea>

初始化编辑器:

ClassicEditor
    .create(document.querySelector('#editor'))
    .catch(error => {
        console.error(error);
    });

实现撤销/重做功能

维护编辑历史记录:

const editor = document.getElementById('editable');
let history = [];
let historyIndex = -1;

editor.addEventListener('input', function() {
    history = history.slice(0, historyIndex + 1);
    history.push(editor.innerHTML);
    historyIndex++;
});

function undo() {
    if (historyIndex > 0) {
        historyIndex--;
        editor.innerHTML = history[historyIndex];
    }
}

function redo() {
    if (historyIndex < history.length - 1) {
        historyIndex++;
        editor.innerHTML = history[historyIndex];
    }
}

保存编辑内容

将编辑内容保存到本地存储:

js实现编辑

function saveContent() {
    const content = document.getElementById('editable').innerHTML;
    localStorage.setItem('savedContent', content);
}

function loadContent() {
    const saved = localStorage.getItem('savedContent');
    if (saved) {
        document.getElementById('editable').innerHTML = saved;
    }
}

标签: 编辑js
分享给朋友:

相关文章

js实现复制功能

js实现复制功能

使用 document.execCommand 方法 这种方法适用于较旧的浏览器,但在现代浏览器中可能被逐步淘汰。通过创建一个临时的 textarea 元素,将文本内容放入其中,然后执行复制命令。…

vue实现编辑

vue实现编辑

Vue 实现编辑功能的方法 在 Vue 中实现编辑功能通常涉及以下几个关键步骤: 数据绑定与表单处理 使用 v-model 实现双向数据绑定,将表单元素与 Vue 实例的数据属性关联起来。例如:…

vue实现图片编辑

vue实现图片编辑

Vue实现图片编辑的方法 使用第三方库vue-cropper 安装vue-cropper库: npm install vue-cropperjs 在Vue组件中使用: <template&g…

elementui编辑

elementui编辑

Element UI 编辑功能实现方法 Element UI 提供了丰富的组件支持数据编辑操作,常见场景包括表格行内编辑、表单编辑、对话框编辑等。 表格行内编辑 使用 el-table 结合 el…

js实现图片滚动

js实现图片滚动

图片滚动的实现方法 使用CSS动画实现 通过CSS的animation和@keyframes可以实现简单的图片滚动效果。这种方法适合静态图片的无缝循环滚动。 <style> .scr…

js 实现按钮点击

js 实现按钮点击

实现按钮点击的 JavaScript 方法 HTML 按钮元素 在 HTML 中创建一个按钮,可以通过 <button> 或 <input> 标签实现: <button…