KindEditor 是一套開源的 HTML 可視化編輯器,主打所見即所得的編輯體驗,兼容 IE、Firefox、Chrome、Safari、Opera 等主流瀏覽器。它用 JavaScript 編寫,能與 Java、.NET、PHP、ASP 等後端技術無縫配合。以上是官網的介紹。
主頁:https://www.kindsoft.net/index.php
下載:https://www.kindsoft.net/down.php
示例:https://www.kindsoft.net/demo.php
項目裡遇到一個情況:客戶直接從 Excel 複製一大段內容粘進編輯器,格式也不整理,原樣保存。Excel 帶過來的樣式標簽又雜又多,前端頁面因此被撐得七零八落。
跟客戶溝通顯然不如自己動手解決。做一層標簽過濾,粘進來的內容會被規整成我們認可的那部分標簽和屬性,問題就消掉了。
第一步是把 filterMode 打開,它默認是關閉狀態:
KindEditor.ready(function (K) { editor = K.create('textarea[name="content"]', { filterMode: true,//是否開啟過濾模式 }); });
僅僅打開還不夠——此時大部分標簽都會被清掉。要通過 htmlTags 參數聲明白名單:哈希表的 key 是 HTML 標簽名,value 是允許保留的屬性數組,以「.」開頭的項表示 style 裡的 CSS 屬性。數據類型是 Object。
KindEditor.ready(function (K) { editor = K.create('textarea[name="content"]', { filterMode: true,//是否開啟過濾模式 htmlTags : { font : ['id', 'class', 'color', 'size', 'face', '.background-color'], div : [ 'id', 'class', 'align', '.border', '.margin', '.padding', '.text-align', '.color', '.background-color', '.font-size', '.font-family', '.font-weight', '.background', '.font-style', '.text-decoration', '.vertical-align', '.margin-left' ], a : ['id', 'class', 'href', 'target', 'name'], embed : ['id', 'class', 'src', 'width', 'height', 'type', 'loop', 'autostart', 'quality', '.width', '.height', 'align', 'allowscriptaccess'], img : ['id', 'class', 'src', 'width', 'height', 'border', 'alt', 'title', 'align', '.width', '.height', '.border'], 'p,ol,ul,li,blockquote,h1,h2,h3,h4,h5,h6' : [ 'id', 'class', 'align', '.text-align', '.color', '.background-color', '.font-size', '.font-family', '.background', '.font-weight', '.font-style', '.text-decoration', '.vertical-align', '.text-indent', '.margin-left' ], pre : ['id', 'class'], hr : ['id', 'class', '.page-break-after'], 'br,tbody,tr,strong,b,sub,sup,em,i,u,strike,s,del' : ['id', 'class'], iframe : ['id', 'class', 'src', 'frameborder', 'width', 'height', '.width', '.height'] } }); });
幾點使用建議:
key 支持用逗號合併多個標簽,像 p、ol、ul、li、標題這幾類排版元素屬性需求接近,寫在一起能省不少重複。
屬性白名單按需增減就好,不必照抄。比如業務上不需要 iframe,直接去掉這一項,過濾會更嚴格。
'.' 前綴控制的是行內樣式,只列出真正需要保留的 CSS 屬性,能有效阻止外部內容挾帶大量骯髒樣式進來。
以上就是關於 KindEditor 開啟 HTML 過濾的全部說明,合理配置白名單之後,從 Office 系軟件粘貼內容的問題基本都能解決。