背景
由于项目的需求使用fastadmin推荐的编辑器kindeditor,使用过程中发现没有段后距这个bug。查询搜索了所有的网上来源,都没有解决方案。鉴宇客户非常需要该功能,奋战几天写端代码实现了该功能。
插件实现
KindEditor.plugin('paragraph', function(K) {var self = this, name = 'paragraph', lang = self.lang(name + '.');self.clickToolbar(name, function() {const iframe = document.querySelector("iframe").contentDocument;var curVal = '', commonNode = self.cmd.commonNode({'*' : '.line-height'});if (commonNode) {curVal = commonNode.css('margin-bottom');}var menu = self.createMenu({name : name,width : 150});K.each(lang.paragaph, function(i, row) {K.each(row, function(key, val) {menu.addItem({title : val,checked : curVal === key + 'px',click : function() {// wrapTextNodes(iframe.body)self.cmd.toggle('<span style="margin-bottom:' + key + 'px;display: block"></span>', {span : '.margin-bottom=' + key});const words = iframe.getSelection().toString()if (iframe.getSelection().rangeCount > 1) {var range = iframe.getSelection().getRangeAt(0);var selectedElement = range.commonAncestorContainer;if (selectedElement.nodeType === Node.TEXT_NODE) {selectedElement = selectedElement.parentNode;}const tag = iframe.body.querySelectorAll("p");const wordsList = words.split("\n\n");let choseCount = 0;for (const el of Array.from(tag)) {let hasChose = false;for (const text of wordsList) {if (el.textContent === text) hasChose = true;}choseCount += hasChose ? 1 : 0;if (hasChose === true) {el.style.marginBottom = curVal + 'px';el.classList.add('selectedMenuItem'); // 添加选中效果} else {el.classList.remove('selectedMenuItem'); // 移除选中效果}}} else {let parentNodelet html = []const copyNodes = [...Array.from(iframe.body.childNodes)]iframe.body.innerHTML = ''copyNodes.forEach(el => {if (!parentNode) parentNode = el.parentNodeif (el.nodeType === 3) {const span = document.createElement('span')span.innerText = el.textContentspan.style.display='block'span.style.marginBottom = valconsole.log(iframe.body, span)iframe.body.appendChild(span)// el.parentNode.replaceChild(span, node)}else {el.style.display = 'block'el.style.marginBottom = valiframe.body.appendChild(el)}})}self.updateState();self.addBookmark();self.hideMenu();}});});});});
});
效果图
初步达到预期效果。后期还有优化地方,共同努力。