简体   繁体   English

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

[英]How to add class or id or CSS style in execCommand formatBlock 'p' tag?

I want to use execcommand 'formatblock' for select a line by 'p' tag or span with specific class or Id or any css style in my contenteditable div(own rich text editor).我想使用 execcommand 'formatblock' 在我的 contenteditable div(自己的富文本编辑器)中通过 'p' 标记或跨度选择具有特定类或 Id 或任何 css 样式的行。 i searched a lot for this, but i could not find anything which valuable for me.我为此搜索了很多,但找不到任何对我有价值的东西。

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

How can i add class or id or css in this code?如何在此代码中添加类或 id 或 css?

If you want to add id or class for CSS in content editable div, then you will use below code---如果您想在内容可编辑的 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;
    }

There are many ways to do it.有很多方法可以做到。 Just use execCommand 'insertHTML' instead to replace selected text with wrapped code.只需使用 execCommand 'insertHTML' 来用包装的代码替换选定的文本。 Like this:像这样:

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

This will remove breaklines, tags like <b> , <i> and other intext-html-formatting - to keep them you need smth like this (thx to post ):这将删除隔断线,像<b><i>和其他 intext-html-formatting 这样的标签 - 为了保留它们,您需要像这样(感谢发布):

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);

This insertHTML does not works with IE.此 insertHTML 不适用于 IE。 Check Documentation https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand检查文档https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand

I got the solution.我得到了解决方案。

Javascript: Javascript:

function line(){

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

HTML HTML

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

This is work perfectly for me.这对我来说是完美的工作。 But i can not make jsfiddle right now.但我现在无法制作 jsfiddle。 This is work for one line fine but not multiple line.这适用于一行,但不适用于多行。

Try this code: http://jsfiddle.net/lotusgodkk/GCu2D/57/试试这个代码: http : //jsfiddle.net/lotusgodkk/GCu2D/57/

Javascript: 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 HTML

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

I had the same issue.我遇到过同样的问题。 I ended up using jQuery.我最终使用了 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' });

There is also this great library that could be helpful: https://github.com/timdown/rangy/wiki/Class-Applier-Module还有这个很棒的库可能会有所帮助: https : //github.com/timdown/rangy/wiki/Class-Applier-Module

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

To add the class to the p tag, I think it should actually be like this...要将类添加到 p 标签中,我认为它实际上应该是这样的......

function CssFnctn() {
  document.execCommand('formatblock', false, 'p')
  var listId = window.getSelection().anchorNode.parentNode;
  listId.classList = 'oder2';
}

Notice the anchorNode instead of focusNode注意 anchorNode 而不是 focusNode

One way to reliably find the element(s) created by execCommand is to compare the list of child elements before and after running it.可靠地找到由execCommand创建的元素的一种方法是比较运行它之前和之后的子元素列表。 Any elements that didin't exist before execCommand was called we're added by execCommand .在调用execCommand之前不存在的任何元素都由execCommand添加。

Here's an example:下面是一个例子:

// `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 

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

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