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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23380628/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 00:47:27  来源:igfitidea点击:

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

javascriptjqueryhtmlcontenteditableexeccommand

提问by Akhi

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). i searched a lot for this, but i could not find anything which valuable for me.

我想使用 execcommand 'formatblock' 在我的 contenteditable div(自己的富文本编辑器)中通过 'p' 标记或跨度选择具有特定类或 Id 或任何 css 样式的行。我为此搜索了很多,但找不到任何对我有价值的东西。

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

How can i add class or id or css in this code?

如何在此代码中添加类或 id 或 css?

回答by Rahmuna

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

回答by kryolite

There are many ways to do it. Just use execCommand 'insertHTML' instead to replace selected text with wrapped code. Like this:

有很多方法可以做到。只需使用 execCommand 'insertHTML' 来用包装的代码替换选定的文本。像这样:

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 格式 - 为了保留它们,您需要像这样(感谢发布):

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. Check Documentation https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand

此 insertHTML 不适用于 IE。检查文档https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand

回答by Akhi

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. This is work for one line fine but not multiple line.

这对我来说是完美的工作。但我现在无法制作 jsfiddle。这适用于一行,但不适用于多行。

回答by K K

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>

回答by Julien Le Coupanec

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

回答by JamieTom

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

回答by Richrd

One way to reliably find the element(s) created by execCommandis to compare the list of child elements before and after running it. Any elements that didin't exist before execCommandwas called we're added by execCommand.

一种可靠地找到创建的元素的方法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