如何使Quill.js解析包含块级元素的嵌套列表?

时间:2017-05-03 00:43:39

标签: javascript html quill

我把这个example in the Quill Playground但是在这里复制了它。

输入HTML

<div id="editor">
  <ol>
    <li>
      <p>Outer Numbered para1</p>
      <p>Outer numbered para2</p>
      <ol>
        <li>Inner Numbered List</li>
      </ol>
    </li>
  </ol>
</div>

的JavaScript

var quill = new Quill('#editor', {
  theme: 'snow'
});

输出HTML

<div class="ql-editor" contenteditable="true">
  <ol>
    <li>Outer Numbered para1</li>
    <li>Outer numbered para2</li>
    <li class="ql-indent-1">Inner Numbered List</li>
  </ol>
</div>

问题

筑巢在哪里?我究竟做错了什么?如何防止嵌套消失或将其取回?

版本

  • Quill 1.2.4版
  • Chrome版本58.0.3029.81(64位)
  • Ubuntu 16.04(64位)

1 个答案:

答案 0 :(得分:0)

您应该在以下情况下规范化嵌套列表值:

你想在你的quilljs编辑器中插入嵌套值,这里有一些代码可能有帮助:

&#13;
&#13;
  function normalizeNestedList(editorValue){


  if(document){
    let tempEditorNode = document.createElement('div');
    tempEditorNode.innerHTML = editorValue;
    const olElems = tempEditorNode.querySelectorAll('ol');
    const ulElems = tempEditorNode.querySelectorAll('ul');
    moveNestedList(olElems);
    moveNestedList(ulElems);

    return tempEditorNode.innerHTML;
  }
}

function moveNestedList(ContainerListElems){
  const quillIntentConst = `ql-indent-`;
  let currentParentToInserted = null;
  for(let i=0; i< ContainerListElems.length; i++){
    const containerListElem = ContainerListElems[i];
    const listDepth = getMaxParents(containerListElem);
    if(listDepth > 0) {
      const containerListElemChilds = containerListElem.childNodes;
      for (let j = 0; j < containerListElemChilds.length; j++) {
        if (containerListElemChilds[j].nodeName === 'LI') {
          containerListElemChilds[j].setAttribute('class',`${quillIntentConst}${listDepth}`);
        }
      }
      insertAfter(currentParentToInserted,containerListElem.outerHTML);
      containerListElem.remove();
    }else {
      currentParentToInserted = containerListElem;
    }
  }
}

function getMaxParents(elem){
  let parentNode = elem.parentNode;
  let count = 0;
  if(parentNode !== null && typeof parentNode !== 'undefined') {
    let nodeName = parentNode.nodeName;
    while (parentNode !== null && typeof parentNode !== 'undefined' && (nodeName === 'UL' || nodeName === 'OL' || nodeName === 'LI')) {
      parentNode = parentNode.parentNode;
      nodeName = parentNode.nodeName;
      if(nodeName === 'UL' || nodeName === 'OL' ) {
        ++count;
      }
    }
  }
  return count;
}

function insertAfter(newNode, referenceNode) {
  newNode.insertAdjacentHTML('afterend', referenceNode);
}
&#13;
&#13;
&#13;

您可以拨打normalizeNestedList功能