使用 npm 或 yarn 安装
npm install froala-editor
# 或者
yarn add froala-editor
在 HTML 文件中引入 Froala 并初始化
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Froala Example</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/froala-editor/4.0.1/css/froala_editor.min.css" rel="stylesheet">
</head>
<body>
<h1>My Froala Example</h1>
<textarea id="editor"></textarea>
<script src="https://cdnjs.cloudflare.com/ajax/libs/froala-editor/4.0.1/js/froala_editor.min.js"></script>
<script>
new FroalaEditor('#editor', {
toolbarButtons: ['bold', 'italic', 'underline', 'strikeThrough', 'formatOL', 'formatUL']
});
</script>
</body>
</html>
1. new FroalaEditor(selector, options)
描述: 初始化 Froala 编辑器并设置配置项。
参数:
selector
: 编辑器要绑定的 DOM 元素选择器。options
: 一个对象,包含配置选项。示例:
new FroalaEditor('#editor', {
toolbarButtons: ['bold', 'italic', 'underline', 'strikeThrough', 'formatOL', 'formatUL']
});
2. editor.html.set(html)
描述: 设置编辑器内容为指定的 HTML。
参数:
html
: 字符串,包含要设置的 HTML 内容。示例:
editor.html.set('<p>This is the new content!</p>');
3. editor.html.get()
描述: 获取编辑器的 HTML 内容。
参数: 无
示例:
let content = editor.html.get();
console.log(content); // 输出当前编辑器内容
4. editor.events.on(eventName, callback)
描述: 为编辑器注册事件监听器。
参数:
eventName
: 字符串,事件名称,如 contentChanged
, focus
, blur
等。callback
: 函数,当事件触发时调用。示例:
editor.events.on('contentChanged', function() {
console.log('Content changed!');
});
5. editor.undo.saveStep()
描述: 保存当前的撤销步骤。
参数: 无
示例:
editor.undo.saveStep();
6. editor.undo.undo()
描述: 执行撤销操作。
参数: 无
示例:
editor.undo.undo();
7. editor.undo.redo()
描述: 执行重做操作。
参数: 无
示例:
editor.undo.redo();
8. editor.image.insert(url, attributes, response)
描述: 在编辑器中插入图片。
参数:
url
: 字符串,图片的 URL。attributes
: 对象,图片的属性。response
: 服务器响应数据。示例:
editor.image.insert('https://example.com/image.jpg', { alt: 'Example image' });
9. editor.destroy()
描述: 销毁编辑器实例。
参数: 无
示例:
editor.destroy();
10. editor.commands.exec(command, param1, param2)
描述: 执行编辑器命令。
参数:
command
: 字符串,命令名称,如 bold
, italic
, insertImage
等。param1
: 命令参数 1。param2
: 命令参数 2。示例:
editor.commands.exec('bold');
自定义插件: Froala 允许开发者创建和集成自定义插件,以扩展编辑器的功能。
示例:
FroalaEditor.PLUGINS.customPlugin = function(editor) {
return {
init: function() {
console.log('Custom plugin initialized');
}
}
};
// 注册插件并使用
new FroalaEditor('#editor', {
toolbarButtons: ['bold', 'italic', 'underline', 'customButton'],
pluginsEnabled: ['customPlugin'],
events: {
'customPlugin.init': function() {
console.log('Custom plugin is being initialized');
}
}
});