Tinymce富文本使用教程

1. 开始

官网文档: w w w . t i n y . c l o u d / d o c s / www.tiny.cloud/docs/ www.tiny.cloud/docs/

社区版及开发版官方最新打包地址: w w w . t i n y . c l o u d / g e t − t i n y / s e l f − h o s t e d / www.tiny.cloud/get-tiny/self-hosted/ www.tiny.cloud/gettiny/selfhosted/

汉化包: t i n y m c e . a x − z . c n / s t a t i c / t i n y / l a n g s / z h C N . j s tinymce.ax-z.cn/static/tiny/langs/zh_CN.js tinymce.axz.cn/static/tiny/langs/zhCN.js

2. 快速使用

引入tinymce脚本

将tinymce初始化为页面的一部分
我们需要使用tinymce.init()来进行初始化;tinymce.init()内的初始化对象包含众多参数,但都是可省略的,唯一必须的参数就是selector(允许通过css选择器指定tinymce要绑定的内容容器,div和textarea都是可以的)

例如:

<div id = "tinydemo"></div>
<script >
    tinymce.init({
        selector: '#tinydemo'
    }); 
</script>

获取tinymce富文本框内容的几种方式:
如果当前页面只有一个编辑器
获取内容:

tinyMCE.activeEditor.getContent()

设置内容:

tinyMCE.activeEditor.setContent("需要设置的编辑器内容")

如果当前页面有多个编辑器(下面的“[0]”表示第一个编辑器,以此类推)
获取内容:

tinyMCE.editors[0].getContent()

设置内容:

tinyMCE.editors[0].setContent("需要设置的编辑器内容")

获取不带HTML标记的纯文本内容

var activeEditor = tinymce.activeEditor;
var editBody = activeEditor.getBody();
activeEditor.selection.select(editBody);
//纯文本内容
var text = activeEditor.selection.getContent({
    'format': 'text'
});

textarea可通过表单提交

<h1>TinyMCE Quick Start Guide</h1>
<form method="post">
      <textarea id="mytextarea">Hello, World!</textarea>
</form>
<script>
      tinymce.init({
        selector: '#mytextarea'
      });
</script>

3. 常用配置

selector

渲染DOM,必填,String值,使用CSS选择器。

language

指定语言,String,值区分大小写。

language_url

汉化包路径

height

设置整个编辑器的高度,包括菜单栏、工具栏和状态栏,如果提供了数字,TinyMCE 以像素为单位设置高度。如果提供了字符串,TinyMCE 假定该值是有效的 CSS,并将编辑器的高度设置为字符串值。这允许备用单元,例如%,em,和vh。(测试%不起作用)

readonly

只读,Boolean,将编辑器设置成只读模式,不可编辑。

plugins

指定需加载的插件,String或Array,此插件必须已存在plugins目录内;若使用String值,多个插件用空格分隔;默认不会加载任何插件,支持自写插件。

可选插件配置: w w w . t i n y . c l o u d / d o c s / p l u g i n s / o p e n s o u r c e / a d v l i s t / www.tiny.cloud/docs/plugins/opensource/advlist/ www.tiny.cloud/docs/plugins/opensource/advlist/

toolbar

自定义工具栏,Boolean或String或Array;为false时将关闭工具栏;String值时用于自定义工具栏,例:toolbar:“link | preview”,值中可插入“|”分组;支持多级工具栏,例:toolbar1:“”,toolbar2:“”;官网: w w w . t i n y . c l o u d / d o c s / c o n f i g u r e / e d i t o r − a p p e a r a n c e / # t o o l b a r www.tiny.cloud/docs/configure/editor-appearance/\#toolbar www.tiny.cloud/docs/configure/editorappearance/#toolbar

menu

自定义菜单。例:

tinymce.init({
    selector: '#tinydemo',
    menu: {
        file: {title: '文件', items: 'newdocument'},
        edit: {title: '编辑', items: 'undo redo | cut copy paste pastetext | selectall'},
        insert: {title: '插入', items: 'link media | template hr'},
        view: {title: '查看', items: 'visualaid'},
        format: {title: '格式', items: 'bold italic underline strikethrough superscript subscript | formats | removeformat'},
        table: {title: '表格', items: 'inserttable tableprops deletetable | cell row column'},
        tools: {title: '工具', items: 'spellchecker code'}
    }
});

当有多级菜单时:

tinymce.init({
    selector: '#tinydemo',
    menubar: 'my1',
    menu: {
        my1: {title: '我的菜单', items: 'copy paste' }
    }
});

menubar

1级菜单,Boolean或String;为false时将关闭菜单栏;String时用于自定义1级菜单,例:menubar:“file edit”;官网: w w w . t i n y . c l o u d / d o c s / c o n f i g u r e / e d i t o r − a p p e a r a n c e / # m e n u b a r www.tiny.cloud/docs/configure/editor-appearance/\#menubar www.tiny.cloud/docs/configure/editorappearance/#menubar

placeholder

内容预展示文本,String值。

resize

调整编辑器大小工具,编辑器右下角有一个可以拖动的标记,鼠标按住它可以改变编辑器的大小。默认resize: true;可选值为:true(仅允许改变高度), false(完全不让你动), ‘both’(宽高都能改变,注意引号)。

4. 高级功能

图片上传

tinymce.init({
    selector: '#tinydemo',
    language: 'zh_CN',
    plugins: 'image', //使用image插件
    toolbar: 'image', //工具栏显示
    images_upload_url: '/api/controller/action', //用于指定一个接收上传文件的后端处理程序地址
    images_upload_base_path: '/demo', //如果返回的地址是相对路径,此参数可以给相对路径指定它所相对的基本路径
});

跨域问题:如果TinyMCE和接受上传图片程序未在同一域名下,浏览器会因跨域问题而拒绝操作,后端程序返回结果时,需给浏览器一个允许跨域的指令。

图片上传扩展参数

名称描述
images_upload_credentials对images_upload_url中指定的地址调用时是否传递cookie等跨域的凭据。值为布尔值,默认false。
images_upload_handler(图片上传自定义实现) 此选项允许你使用自定义函数代替TinyMCE来处理上传操作。该自定义函数需提供4个参数:blobInfo、成功回调和失败回调、上传进度(取值1-100)。
images_upload_handler函数将完全接管编辑器的图片上传,你需要在上传成功后执行成功回调函数,参数则为图片URL,也可以在第二个参数加入对话框填充数据对象。
//以下为自定义上传实现的一个代码示例
tinymce.init({
    selector: '#tinydemo',
    images_upload_handler: function(blobInfo, success, failure, progress) {
        var xhr, formData;
        xhr = new XMLHttpRequest();
        xhr.withCredentials = false;
        xhr.open('POST', 'action');
 
        xhr.upload.onprogress = function(e) {
            progress(e.loaded / e.total * 100);
        }
 
        xhr.onload = function() {
            var json;
            if (xhr.status == 403) {
                failure('HTTP Error: ' + xhr.status, {
                    remove: true
                });
                return;
            }
            if (xhr.status < 200 || xhr.status >= 300) {
                failure('HTTP Error: ' + xhr.status);
                return;
            }
            json = JSON.parse(xhr.responseText);
            if (!json || typeof json.location != 'string') {
                failure('Invalid JSON: ' + xhr.responseText);
                return;
            }
            success(json.location);
        };
 
        xhr.onerror = function() {
            failure('Image upload failed due to a XHR Transport error. Code: ' + xhr.status);
        }
 
        formData = new FormData();
        formData.append('file', blobInfo.blob(), blobInfo.filename());
 
        xhr.send(formData);
    }
});

文件上传

原文里只涉及了图片上传,文件上传没有说明,只能使用 file_picker_callback 写回调。
更多参数请移步官网:www.tiny.cloud/docs/configure/file-image-upload/#automatic_uploads

简单例子:

tinymce.init({
    selector: '#tinydemo',
    language: 'zh_CN',
    plugins: 'link',        
    toolbar: 'link',            
    file_picker_callback: function(callback, value, meta) {
    //文件分类
    var filetype = '.pdf, .txt, .zip, .rar, .7z, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .mp3, .mp4';
    var upurl = '/api/controller/';
    //为不同插件指定文件类型及后端地址
    switch (meta.filetype) {
        case 'image':
            filetype = '.jpg, .jpeg, .png, .gif';
            upurl += 'action1';
            break;
        case 'media':
            filetype = '.mp3, .mp4';
            upurl += 'action2';
            break;
            case 'file':
                break;
    };
    //模拟出一个input用于添加本地文件
    var input = document.createElement('input');
    input.setAttribute('type', 'file');
    input.setAttribute('accept', filetype);
    input.click();
    input.onchange = function() {
        var file = this.files[0];
        var xhr, formData;
        console.log(file.name);
        //TODO:这里写请求
        };
    },            
});                

自定义插件

第一,在目录tinymce/plugins下新建一个目录,与自己要取的插件名称相同,在到插件目录下新建plugin.min.js,如下:
u p f i l e / p l u g i n . m i n . j s upfile/plugin.min.js upfile/plugin.min.js
upfile是我自定义插件名称,位置 t i n y m c e / p l u g i n s / u p f i l e tinymce/plugins/upfile tinymce/plugins/upfile

第二,理解下面代码,参阅官网:
w w w . t i n y . c l o u d / d o c s / a p i / t i n y m c e / t i n y m c e . a d d o n m a n a g e r / www.tiny.cloud/docs/api/tinymce/tinymce.addonmanager/ www.tiny.cloud/docs/api/tinymce/tinymce.addonmanager/

/**
 * 上传文件插件
 */
 
tinymce.PluginManager.add('upfile', function (editor, url) {
    var openDialog = function () {
        return editor.windowManager.open({
            title: '上传文件',
            body: {
                type: 'panel',
                items: [
                    {
                        type: 'htmlpanel', // component type
                        html: '<div><input id="TinymcefileToUpload" type="file"  name="TinymcefileToUpload" class="input"></div>'
                    }
                ]
            },
            buttons: [
                {
                    type: 'cancel',
                    text: 'Close'
                },
                {
                    type: 'submit',
                    text: 'Upload',
                    primary: true
                }
            ],
            onSubmit: function (api) {
                let input = document.getElementById("TinymcefileToUpload");
                console.log("进来了");
                if (input.files.length > 0) {
                    let file = input.files[0];
                    let formData = new FormData();
                    formData.append("formFile", file);
                    axios.post("https://192.168.0.174:7183/api/Test/UploadFile", formData).then(res => {
                        if (res.data?.path != "") {
                            editor.insertContent(res.data.fileName + ":" + res.data?.path);
                            alert("文件上传成功");
                        }
                        else {
                            alert("上传失败");
                        }
                    }).catch(err => console.log(err));
                }
                api.close();
            }
        });
    };
 
    // Add a button that opens a window
    editor.ui.registry.addButton('upfile', {
        text: `<svg xmlns="http://www.w3.org/2000/svg" width="30" height="30" fill="currentColor" class="bi bi-box-arrow-in-up" viewBox="0 0 16 16">
            < path fill- rule="evenodd" d = "M3.5 10a.5.5 0 0 1-.5-.5v-8a.5.5 0 0 1 .5-.5h9a.5.5 0 0 1 .5.5v8a.5.5 0 0 1-.5.5h-2a.5.5 0 0 0 0 1h2A1.5 1.5 0 0 0 14 9.5v-8A1.5 1.5 0 0 0 12.5 0h-9A1.5 1.5 0 0 0 2 1.5v8A1.5 1.5 0 0 0 3.5 11h2a.5.5 0 0 0 0-1h-2z" />
            <path fill-rule="evenodd" d="M7.646 4.146a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1-.708.708L8.5 5.707V14.5a.5.5 0 0 1-1 0V5.707L5.354 7.854a.5.5 0 1 1-.708-.708l3-3z" />
      </svg> `,
        onAction: function () {
            // Open window
            openDialog();
        }
    });
 
    // Adds a menu item, which can then be included in any menu via the menu/menubar configuration
    editor.ui.registry.addMenuItem('upfile', {
        text: 'Example plugin',
        onAction: function () {
            // Open window
            openDialog();
        }
    });
 
    return {
        getMetadata: function () {
            return {
                name: "Example plugin",
                url: "http://exampleplugindocsurl.com"
            };
        }
    };
});

第三,笔者理解 不难看出,这是一个自写文件上传插件,需要注意的是该插件基于tinymce5.x,5.x以下会报错; 回到代码,其中upfile是插件名; openDialog()是用于打开弹窗; editor.windowManager.open用于自定义弹窗主题内容以及按钮回调; title是弹窗标题; body是弹窗中间内容; 上述插件使用的是一个容器包含很多子项,子项其中用了html容器,该容器支持html输出; buttons弹窗按钮集合;onSubmit是提交按钮触发事件; editor.ui.registry用于添加自定义项,具体参考: w w w . t i n y . c l o u d / d o c s / a p i / t i n y m c e . e d i t o r . u i / t i n y m c e . e d i t o r . u i . r e g i s t r y / # m e t h o d s www.tiny.cloud/docs/api/tinymce.editor.ui/tinymce.editor.ui.registry/\#methods www.tiny.cloud/docs/api/tinymce.editor.ui/tinymce.editor.ui.registry/#methods

5.使用typo排版

引入typo.css,给div加上"class=‘typo’"即可自动排版,详情参阅:typo.sofi.sh

typo.css局域网地址: f i l e : / / d e s k t o p − b 9 p r p k g / e n j o y / t y p o . c s s file://desktop-b9prpkg/enjoy/typo.css file://desktopb9prpkg/enjoy/typo.css

6.tinymce-vue(不推荐)

a.快速使用

本节基于vue2演示 首先,使用vuecli创建项目

vue create vue -demo

进入项目目录后,安装tinymce-vue

npm install --save "@tinymce/tinymce-vue@^3"

完整使用:

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png" />
    <HelloWorld msg="Welcome to Your Vue.js App" />
    <editor api-key="no-api-key" :init="initME" />
  </div>
</template>
 
<script src="http://tinymce.ax-z.cn/static/tiny/langs/zh_CN.js"></script>
<script>
import HelloWorld from "./components/HelloWorld.vue";
import Editor from "@tinymce/tinymce-vue";
 
export default {
  name: "App",
  components: {
    HelloWorld,
    Editor,
  },
  data() {
    return {
      initME: {
        height: 500,
        language: "zh_CN",
        plugins: [
          "advlist autolink lists link image charmap print preview anchor",
          "searchreplace visualblocks code fullscreen",
          "insertdatetime media table paste code help wordcount",
        ],
        toolbar:
          "undo redo | formatselect | bold italic backcolor | \
           alignleft aligncenter alignright alignjustify | \
           bullist numlist outdent indent | removeformat | help",
      },
    };
  },
  mounted() {
    tinymce.init({});
},
};
</script>

b.组件配置项

api-key

Tiny Cloud API 密钥。使用 Tiny Cloud 进行部署时需要提供 TinyMCE 编辑器。 默认值: no-api-key,类型:String.

cloud-channel

不详

disabled

该disabled属性可以在“禁用”(只读)模式 ( true) 和标准可编辑模式 ( false)之间动态切换编辑器。

id

编辑器的id.用于使用该tinymce.get(‘id’)方法检索编辑器实例。默认为自动生成的UUID.

init

对象发送到tinymce.init用于初始化编辑器的方法,同配置。

initial-value

编辑器初始化时编辑器的初始内容,与原生placeholder用法一致。

inline

是否开启内联模式,默认false.

model-events

更改要触发v-model事件的事件,默认为’change keyup’

output-format

用于指定通过input事件发出的内容的格式。这会影响与数据绑定一起使用的内容的格式。 默认值:html.可选择:html,text.

plugins

插件,同plugins.

tag-name

仅当inline=true时有效,用于为内联模式的编辑器定义HTML元素。

toolbar

工具栏,同toolbar.

tinymce-script-src

使用tinymce-script-srcprop 指定 TinyMCE 的外部版本以进行延迟加载,String值,例:

<editor
  tinymce-script-src="/path/to/tinymce.min.js"
/>

v-model

指令可用于创建双向数据绑定。

selectionChange

事件绑定,详细请参阅: w w w . t i n y . c l o u d / d o c s / i n t e g r a t i o n s / v u e / # e v e n t b i n d i n g www.tiny.cloud/docs/integrations/vue/\#eventbinding www.tiny.cloud/docs/integrations/vue/#eventbinding

7.自定义在vue中使用(推荐)

第一,引入,例:

<script src="../tinymce/tinymce.min.js"></script>

第二,创建div或textarea,例:

<div id="tinymcedemo"></div>

第三,tinymce初始化方法写入vue实例的methods属性,例:

methods:{
    init(){
        window.tinymce.init({
            selector:"#tinymcedemo"
        })
    }
}

第四,挂载,例:

mounted(){
    this.init();
}

挂载完成后,就可以使用了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Code Writers

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值