自定义工具栏

Custom toolbar (icons handler)

x
1
### Custom toolbar
2
3
```javascript
4
$(function() {
5
    var testEditor = editormd("test-editormd", {
6
        width: "90%",
7
        height: 640,
8
        path : '../lib/',
9
        toolbarIcons : function() {
10
            // Or return editormd.toolbarModes[name]; // full, simple, mini
11
            // Using "||" set icons align right.
12
            return ["undo", "redo", "|", "bold", "hr", "|", "preview", "watch", "|", "fullscreen", "info", "testIcon", "testIcon2", "file", "faicon", "||", "watch", "fullscreen", "preview", "testIcon"]
13
        },
14
        toolbarIconsClass : {
15
            testIcon : "fa-gears"  // 指定一个FontAawsome的图标类
16
        },
17
        toolbarIconTexts : {
18
            testIcon2 : "测试按钮"  // 如果没有图标,则可以这样直接插入内容,可以是字符串或HTML标签
19
        },
20
21
        // 用于增加自定义工具栏的功能,可以直接插入HTML标签,不使用默认的元素创建图标
22
        toolbarCustomIcons : {
23
            file   : "<input type="file" accept=".md" />",
24
            faicon : "<i class="fa fa-star" onclick="alert('faicon');"></i>"
25
        },
26
27
        // 自定义工具栏按钮的事件处理
28
        toolbarHandlers : {
29
            /**
30
             * @param {Object}      cm         CodeMirror对象
31
             * @param {Object}      icon       图标按钮jQuery元素对象
32
             * @param {Object}      cursor     CodeMirror的光标对象,可获取光标所在行和位置
33
             * @param {String}      selection  编辑器选中的文本
34
             */
35
            testIcon : function(cm, icon, cursor, selection) {
36
37
                //var cursor    = cm.getCursor();     //获取当前光标对象,同cursor参数
38
                //var selection = cm.getSelection();  //获取当前选中的文本,同selection参数
39
40
                // 替换选中文本,如果没有选中文本,则直接插入
41
                cm.replaceSelection("[" + selection + ":testIcon]");
42
43
                // 如果当前没有选中的文本,将光标移到要输入的位置
44
                if(selection === "") {
45
                    cm.setCursor(cursor.line, cursor.ch + 1);
46
                }
47
48
                // this == 当前editormd实例
49
                console.log("testIcon =>", this, cm, icon, cursor, selection);
50
            },
51
52
            testIcon2 : function(cm, icon, cursor, selection) {
53
                cm.replaceSelection("[" + selection + ":testIcon2](" + icon.html() + ")");
54
                console.log("testIcon2 =>", this, icon.html());
55
            }
56
        },
57
58
        lang : {
59
            toolbar : {
60
                file : "上传文件",
61
                testIcon : "自定义按钮testIcon",  // 自定义按钮的提示文本,即title属性
62
                testIcon2 : "自定义按钮testIcon2",  
63
                undo : "撤销 (Ctrl+Z)"
64
            }
65
        },
66
67
        onload : function(){
68
            $("[type=\"file\"]").bind("change", function(){
69
                alert($(this).val());
70
                testEditor.cm.replaceSelection($(this).val());
71
                console.log($(this).val(), testEditor);
72
            });
73
        }
74
    });
75
});
76
```
77