1. 程式人生 > >Bootstrap -- 富文字編輯器bootstrap-wysiwyg的使用方法

Bootstrap -- 富文字編輯器bootstrap-wysiwyg的使用方法


<\/div>| )*$/, ''); }; $.fn.wysiwyg = function (userOptions) { var editor = this, //設定ui-jq='設定的外掛別名的dom元素'(此句註釋可忽略,是針對我的專案結構寫的) selectedRange, options, toolbarBtnSelector, //更新工具欄 updateToolbar = function () { if (options.activeToolbarClass) { $(options.toolbarSelector).find(toolbarBtnSelector).each(function () { var command = $(this).data(options.commandRole); //判斷游標所在位置以確定命令的狀態,為真則顯示為啟用 if (document.queryCommandState(command)) { $(this).addClass(options.activeToolbarClass); } else { $(this).removeClass(options.activeToolbarClass); } }); } }, //插入內容 execCommand = function (commandWithArgs, valueArg) { var commandArr = commandWithArgs.split(' '), command = commandArr.shift(), args = commandArr.join(' ') + (valueArg || ''); document.execCommand(command, 0, args); updateToolbar(); }, //用jquery.hotkeys.js外掛監聽鍵盤 bindHotkeys = function (hotKeys) { $.each(hotKeys, function (hotkey, command) { editor.keydown(hotkey, function (e) { if (editor.attr('contenteditable') && editor.is(':visible')) { e.preventDefault(); e.stopPropagation(); execCommand(command); } }).keyup(hotkey, function (e) { if (editor.attr('contenteditable') && editor.is(':visible')) { e.preventDefault(); e.stopPropagation(); } }); }); }, //獲取當前range物件 getCurrentRange = function () { var sel = window.getSelection(); if (sel.getRangeAt && sel.rangeCount) { return sel.getRangeAt(0); //從當前selection物件中獲得一個range物件。 } }, //儲存 saveSelection = function () { selectedRange = getCurrentRange(); }, //恢復 restoreSelection = function () { var selection = window.getSelection(); //獲取當前既獲區,selection是對當前啟用選中區(即高亮文字)進行操作 if (selectedRange) { try { //移除selection中所有的range物件,執行後anchorNode、focusNode被設定為null,不存在任何被選中的內容。 selection.removeAllRanges(); } catch (ex) { document.body.createTextRange().select(); document.selection.empty(); } //將range新增到selection當中,所以一個selection中可以有多個range。 //注意Chrome不允許同時存在多個range,它的處理方式和Firefox有些不同。 selection.addRange(selectedRange); } }, //插入檔案(這裡指圖片) 這裡插入檔案之後需要把檔案轉化為base64編碼,然後通過readFileIntoDataUrl轉碼成圖片 insertFiles = function (files) { editor.focus(); //遍歷插入(應為可以多檔案插入) $.each(files, function (idx, fileInfo) { //只可插入圖片檔案 if (/^image\//.test(fileInfo.type)) { // 如果想對照片做一些操作,可以在照片轉碼之前,把照片放入你需要的陣列中,這個只是本專案中需要 //轉碼圖片 $.when(readFileIntoDataUrl(fileInfo)) .done(function (dataUrl) { execCommand('insertimage', dataUrl); //插入圖片dom及src屬性值 }) .fail(function (e) { options.fileUploadError("file-reader", e); }); } else { //非圖片檔案會呼叫config的錯誤函式 options.fileUploadError("unsupported-file-type", fileInfo.type); } }); }, //TODO 暫不瞭解用意 markSelection = function (input, color) { restoreSelection(); //確定命令是否被支援,返回true或false if (document.queryCommandSupported('hiliteColor')) { document.execCommand('hiliteColor', 0, color || 'transparent'); } saveSelection(); input.data(options.selectionMarker, color); }, //繫結工具欄相應工具事件 bindToolbar = function (toolbar, options) { //給所有工具欄上的控制元件繫結點選事件 toolbar.find(toolbarBtnSelector).click(function () { restoreSelection(); editor.focus(); //獲取焦點 //設定相應配置的工具execCommand execCommand($(this).data(options.commandRole)); //儲存 saveSelection(); }); //對[data-toggle=dropdown]進行單獨繫結點選事件處理 字型大小 toolbar.find('[data-toggle=dropdown]').click(restoreSelection); //對input控制元件進行單獨處理,webkitspeechchange為語音事件 toolbar.find('input[type=text][data-' + options.commandRole + ']').on('webkitspeechchange change', function () { var newValue = this.value; //獲取input 的value this.value = ''; //清空value防止衝突 restoreSelection(); if (newValue) { editor.focus();//獲取焦點 //設定相應配置的工具execCommand execCommand($(this).data(options.commandRole), newValue); } saveSelection(); }).on('focus', function () { //獲取焦點 var input = $(this); if (!input.data(options.selectionMarker)) { markSelection(input, options.selectionColor); input.focus(); } }).on('blur', function () { //失去焦點 var input = $(this); if (input.data(options.selectionMarker)) { markSelection(input, false); } }); toolbar.find('input[type=file][data-' + options.commandRole + ']').change(function () { restoreSelection(); if (this.type === 'file' && this.files && this.files.length > 0) { insertFiles(this.files); } saveSelection(); this.value = ''; }); }, //初始化拖放事件 initFileDrops = function () { editor.on('dragenter dragover', false) .on('drop', function (e) { var dataTransfer = e.originalEvent.dataTransfer; e.stopPropagation(); e.preventDefault(); if (dataTransfer && dataTransfer.files && dataTransfer.files.length > 0) { insertFiles(dataTransfer.files); } }); }; //合併傳入的配置物件userOptions和預設的配置物件config options = $.extend({}, $.fn.wysiwyg.defaults, userOptions); //設定查詢字串:a[data-edit] button[data-edit] input[type=button][data-edit] toolbarBtnSelector = 'a[data-' + options.commandRole + '],button[data-' + options.commandRole + '],input[type=button][data-' + options.commandRole + ']'; //設定熱鍵 容器有[data-role=editor-toolbar]屬性的dom元素 bindHotkeys(options.hotKeys); //是否允許拖放 允許則配置拖放 if (options.dragAndDropImages) {initFileDrops();} //配置工具欄 bindToolbar($(options.toolbarSelector), options); //設定編輯區域為可編輯狀態並繫結事件mouseup keyup mouseout editor.attr('contenteditable', true) .on('mouseup keyup mouseout', function () { saveSelection(); updateToolbar(); }); //編輯區域繫結圖片點選事件 //TODO 這是我自己新增的,因為有時要對圖片進行一些操作 editor.on('mousedown','img', function (e) { e.preventDefault(); }).on('click', 'img', function (e) { var $img = $(e.currentTarget); console.log($img); e.preventDefault(); e.stopPropagation(); }); //window繫結touchend事件 $(window).bind('touchend', function (e) { var isInside = (editor.is(e.target) || editor.has(e.target).length > 0), currentRange = getCurrentRange(), clear = currentRange && (currentRange.startContainer === currentRange.endContainer && currentRange.startOffset === currentRange.endOffset); if (!clear || isInside) { saveSelection(); updateToolbar(); } }); return this; }; //配置引數 $.fn.wysiwyg.defaults = { hotKeys: { //熱鍵 應用hotkeys.js jquery外掛 'ctrl+b meta+b': 'bold', 'ctrl+i meta+i': 'italic', 'ctrl+u meta+u': 'underline', 'ctrl+z meta+z': 'undo', 'ctrl+y meta+y meta+shift+z': 'redo', 'ctrl+l meta+l': 'justifyleft', 'ctrl+r meta+r': 'justifyright', 'ctrl+e meta+e': 'justifycenter', 'ctrl+j meta+j': 'justifyfull', 'shift+tab': 'outdent', 'tab': 'indent' }, toolbarSelector: '[data-role=editor-toolbar]', commandRole: 'edit', activeToolbarClass: 'btn-info', selectionMarker: 'edit-focus-marker', selectionColor: 'darkgrey', dragAndDropImages: true, //是否支援拖放,預設為支援 fileUploadError: function (reason, detail) { console.log("File upload error", reason, detail); } }; }(window.jQuery));