首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使Quill.js解析包含块级元素的嵌套列表?

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

Stack Overflow用户
提问于 2017-05-03 00:43:39
回答 1查看 1.8K关注 0票数 0

我把这个在Quill游乐场的例子放在这里,但在这里复制它。

输入HTML

代码语言:javascript
运行
复制
<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

代码语言:javascript
运行
复制
var quill = new Quill('#editor', {
  theme: 'snow'
});

输出HTML

代码语言:javascript
运行
复制
<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位)
EN

回答 1

Stack Overflow用户

发布于 2017-07-25 10:06:01

在以下情况下,应将嵌套的列表值规范化:

您希望在quilljs编辑器中插入嵌套值,下面的代码可能会有所帮助:

代码语言:javascript
运行
复制
  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);
}

您可以调用normalizeNestedList函数

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43749322

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档