[英]How to implement a code button in a javascript wysiwyg editor
I try to build my own WYSIWYG editor in javascript.我尝试在 javascript 中构建自己的所见即所得编辑器。 Most of the buttons are quite simple (as long as document.execCommand has a commandId).
大多数按钮都非常简单(只要 document.execCommand 有一个 commandId)。
But how to implement a code option like in StackOverflow editor.但是如何在 StackOverflow 编辑器中实现代码选项。
What I tried:我尝试了什么:
document.execCommand('formatBlock', '<pre><code>')
Unfortunately, it is not working.不幸的是,它不起作用。 What I'm doing wrong?
我做错了什么?
The <code>
tag is not part of the list of supported tags for formatBlock . <code>
标签不是formatBlock支持标签列表的一部分。 You can however insert a <pre>
tag by using:但是,您可以使用以下方法插入
<pre>
标记:
document.execCommand('formatBlock', false, '<pre>');
You can check the w3c documentation for a list of supported tags (it depends on the browser).您可以查看w3c 文档以获取支持的标签列表(取决于浏览器)。
If you do not care about IE, you can use the insertHTML
option, combined together with document.getSelection()
, like so:如果你不关心 IE,你可以使用
insertHTML
选项,结合document.getSelection()
,像这样:
document.execCommand('insertHTML', false, `<pre><code>${document.getSelection()}</code></pre>`)
Or you could implement the functionality yourself.或者您可以自己实现该功能。 As pointed out by others,
document.execCommand
is now obsolete , so it might be your safest option, depending on which browsers you need to support.正如其他人指出的那样,
document.execCommand
现在已过时,因此它可能是您最安全的选择,具体取决于您需要支持的浏览器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.