简体   繁体   English

在Chrome中使用document.execCommand(“ insertorderedlist”)丢失样式

[英]Styles getting lost using document.execCommand(“insertorderedlist”) in Chrome

The following snippet loses custom styles on Chrome, but not on Firefox: 以下代码段在Chrome上丢失了自定义样式,但在Firefox上却未丢失:

  document.getElementById( 'run' ).addEventListener( 'click', function() { document.execCommand("insertorderedlist"); } ); 
  <div contenteditable="true"> <p><span style="font-weight: bold;">line 1</span></p> <p><span style="font-style: italic;">line 2</span></p> <p><span style="text-decoration-line: underline;">line 3</span></p> </div> <button id="run">Select the above text and click me</button> 

Is there a known workaround for this? 是否有已知的解决方法? I can't find any documentation about it. 我找不到有关它的任何文档。

You would need to get the style of the selections common ancestor (which, in this case, is a text node, so you'll have to get the parentNode), and apply it to the new selections common ancestor: 您将需要获取选择共同祖先的样式(在这种情况下,它是一个文本节点,因此您必须获取parentNode),并将其应用于新的选择共同祖先:

 document.getElementById( 'run' ).addEventListener( 'click', function() { sel = window.getSelection(); if (sel.rangeCount) { let selection = sel.getRangeAt(0); if (selection.startContainer.parentNode.tagName === 'SPAN') { let startNode = selection.startContainer.parentNode.parentNode; let endNode = selection.endContainer.parentNode.parentNode; let styles = [startNode.firstChild.style.cssText]; while(startNode && !startNode.isEqualNode(endNode)) { startNode = startNode.nextElementSibling || startNode.nextSibling; styles.push(startNode.firstChild.style.cssText); } document.execCommand("insertorderedlist"); selection = sel.getRangeAt(0); startNode = selection.startContainer.parentNode; endNode = selection.endContainer.parentNode; newNodes = [startNode]; while(startNode && !startNode.isEqualNode(endNode)) { startNode = startNode.nextElementSibling || startNode.nextSibling; newNodes.push(startNode); } for (var i = 0; i < newNodes.length; i++) { newNodes[i].style = styles[i]; } } else { if (sel.rangeCount) { let ancestor = sel.getRangeAt(0).commonAncestorContainer.parentNode; document.execCommand("insertorderedlist"); sel.getRangeAt(0).commonAncestorContainer.parentNode.style = ancestor.style.cssText; } } } } ); 
 <div contenteditable="true"> <p><span style="font-weight: bold;">line 1</span></p> <p><span style="font-style: italic;">line 2</span></p> <p><span style="text-decoration-line: underline;">line 3</span></p> </div> <button id="run">Select the above text and click me</button> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM