如何在execCommand的formatBlock 'p'标签中添加类、ID或CSS样式?

8

我希望在自己的富文本编辑器中使用execcommand 'formatblock'命令,以选择由'p'标签、特定类或Id、任何css样式定义的行。我已经搜索了很多资料,但都没有找到对我有价值的内容。

document.execCommand('formatblock', false, 'p');

我该如何在这段代码中添加类(class)、id或CSS样式?
请问您需要添加的具体内容是什么?
7个回答

12

如果您想为可编辑的 div 添加 CSS 的 id 或 class,则可以使用以下代码 ---

          <script>
             function CssFnctn()
                {
                  document.execCommand('formatblock', false, 'p')
                  var listId = window.getSelection().focusNode.parentNode;
                  $(listId).addClass("oder2");
                 }
           </script>


.oder2
    {
       padding-left: 3em;
    }

2
不是很可靠。通常你可以得到文本选择的相邻节点,而不是新的 p - Tim
1
@Tim 是的,我也遇到了这个问题。有其他的解决方案吗? - Ankur Aggarwal
@Ankur Aggarwal:我没想出来。最后我放弃了contenteditable,改用Markdown。如果Web标准得到改进,我可能会回到contenteditable。 - Tim
应该是 window.getSelection().focusNode 而不是带有 parentNode - Ahtisham

5

有很多方法可以实现它。只需使用 execCommand 'insertHTML',将选定的文本替换为包装的代码即可。像这样:

selection = window.getSelection().toString();
wrappedselection = '<span class="accent" style="somestyle">' + selection + '</span>';
document.execCommand('insertHTML', false, wrappedselection);

这将会移除掉换行符,像<b><i>和其他的内部HTML格式标签——如果你想要保留它们,你需要像这样做(感谢这篇文章):

selection = window.getSelection().getRangeAt(0).cloneContents();
span = document.createElement('span');
span.appendChild(selection);
wrappedselection = '<span class="accent1">'+span.innerHTML+'</span>';
document.execCommand('insertHTML', false, wrappedselection);

这个insertHTML在IE上不起作用。请查阅文档https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand


3

I got the solution.

Javascript:

function line(){

              window.execCommand('formatblock', false, 'p');
                selectedElement = window.getSelection().focusNode.parentNode;
                selectedElement.style.marginBottom = '100px';
            }

HTML

<input type="button" value="addMarginBottom" onclick="javascript:line();"/>
<div class="textcontent" contenteditable ="true"></div>

这对我来说完全可以工作。但是我现在无法制作jsfiddle。这对单行正常工作,但不适用于多行。


1

请尝试以下代码:http://jsfiddle.net/lotusgodkk/GCu2D/57/

Javascript:

$(document).ready(function () {
    $('div').click(function () {
     var sel = window.getSelection();
     var range = document.createRange();
     el = document.getElementById('one'); //Get the element
     range.selectNodeContents(el);
     sel.removeAllRanges();
     sel.addRange(range);
     document.execCommand('formatblock', false, null); //execute command.
     document.execCommand('bold', false, null); //execute command.
    });
});

HTML

<div contenteditable="true">
  <p id="one">Sample text</p>
  <p>Sample text 2</p>
</div>

实际上,当我将光标放在 div 的一行中时,然后单击属于 execcommand formatblock 'P' 的按钮。然后,该行文本将进入 p 标签。我的问题是——是否可以为此 p 标签添加任何类、ID 或 CSS? - Akhi
那么,当您在p标签中添加一行文本时,焦点会集中在p标签上,对吗?如果是的话,那么您可以通过以下方式选择聚焦元素,然后在其上添加类/样式://获取聚焦元素: var $focused = $(':focus');//无jQuery: var focused = document.activeElement;//元素是否具有焦点: var hasFocus = $('foo').is(':focus');//无jQuery: elem === elem.ownerDocument.activeElement;如果我误解了您的问题,请纠正我。 - K K
你能给我任何例子吗? - Akhi
你应该为你的代码创建一个"fiddle",并在"P"标签中添加一行文本。这样我就可以更容易地帮助你了。 - K K

1
为了将类添加到p标签中,我认为实际上应该像这样...
function CssFnctn() {
  document.execCommand('formatblock', false, 'p')
  var listId = window.getSelection().anchorNode.parentNode;
  listId.classList = 'oder2';
}

注意 anchorNode 而不是 focusNode。

0

我曾经遇到过同样的问题,最终我使用了jQuery。

document.execCommand(optionCommand, false, null);

let snippets = $('.js-editor-content-snippet');
let lists = snippets.find('ul, ol');

lists.css({ margin: '0', padding: '0 0 0 20px' });
lists.find('li').css({ margin: '0 0 12px' });

还有一个非常棒的库可能会很有帮助:https://github.com/timdown/rangy/wiki/Class-Applier-Module

rangy.createClassApplier(String theClass[, Object options[, Array tagNames]])

0

可靠地找到由 execCommand 创建的元素的一种方法是比较运行之前和之后的子元素列表。任何在调用 execCommand 之前不存在的元素都是由 execCommand 添加的。

以下是一个例子:

// `container` is the contenteditable container element
// Get all the existing elements
const elementsBefore = Array.from(container.querySelectorAll("*"));
// Run the command (wrap selection in a p tag)
document.execCommand("formatblock", false, "p");
// Get all the existing elements again
const elementsAfter = Array.from(container.querySelectorAll("*"));
// Find any that elements didn't exist before `execCommand` and select the first one
const newElement = elementsAfter.filter(e => !elementsBefore.includes(e))[0]
// `newElements` should now be the p tag that was added 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接