Firefox中的insertUnorderedList错误

时间:2018-04-07 17:55:30

标签: javascript html firefox

我正在构建WYSIWYG编辑器。目前我正在努力插入无序列表。我正在使用document.execCommand('insertUnorderedList')。以下是演示:



div[contenteditable] {
  width: 500px;
  height: 300px;
  border: 1px solid black;
}

<button onclick="document.execCommand('insertUnorderedList')">insert unordered list</button>
<div contenteditable="true" spellcheck="false"><p>First line</p><p>Secound line</p><p>Third line</p><p>Fourth line</p><p>Fifth line</p><p>Sixth line</p>
</div>
&#13;
&#13;
&#13;

这里的一切都有效,但我发现了错误。我不知道你是否也有这种情况(因为当我在IE中尝试这个时,而不是Firefox,一切正常),但是做一个实验:

1. Select lines sixth, fifth and fourth (last three)
2. Click button
3. Select lines fifth, fourth and third
4. Click button

之后你会看到一个<ul>有四个<li>,但我看到一些奇怪的东西:第二个列表(<ul>)出现了。喜欢图像:
enter image description here

我不知道怎么可能以及如何修复它。如果你知道请帮助我。感谢。

1 个答案:

答案 0 :(得分:0)

此代码应该适用于每个浏览器(但我只在Firefox中测试过)。注意:此代码使用JQuery。

&#13;
&#13;
$('button').click(function() {
  document.execCommand('insertUnorderedList');
  
  //Remove empty lines
  $('ul > li > br').parent().remove();

	//Target new list
  var newList = $('ul:not(.ordered)');

  //If element after new list is previously created list, combine them in one list
  if (newList.next('ul:not(.ordered)').length > 0) {
    newList.append(newList.next().detach().contents().unwrap());
  }

  //If element before new list is previously created list, combine them in one list
  if (newList.prev('ul:not(.ordered)').length > 0) {
    newList.prepend(newList.prev().detach().contents().unwrap());
  }

  newList.addClass('ordered');
});
&#13;
div[contenteditable] {
  width: 500px;
  height: 300px;
  border: 1px solid black;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>insert unordered list</button>
<div contenteditable="true" spellcheck="false">
  <p>First line</p>
  <p>Secound line</p>
  <p>Third line</p>
  <p>Fourth line</p>
  <p>Fifth line</p>
  <p>Sixth line</p>
</div>
&#13;
&#13;
&#13;