在 html 中制作所见即所得的编辑器

Make wysiwyg editor in html

我将为 html 创建一个所见即所得的 1 编辑器。我已经制作了一个文本区域,但是如何为它制作一个所见即所得的编辑器呢?如果文本区域像下面的代码片段一样实现 html 标签,我会很容易,但事实并非如此。如何制作这个所见即所得的编辑器?

<textarea cols="30" rows="10">
    <h1>Title</h1>
    <hr/>
    <p>Some text</p>
    <ul>
        <li>a</li>
        <li>b</li>
        <li>c</li>
    </ul>
</textarea>

1 what you see is what you get

您可以使用以下代码...

 window.addEventListener("load", function(){
    //first check if execCommand and contentEditable attribute is supported or not.
    if(document.contentEditable != undefined && document.execCommand != undefined)
   {
       alert("HTML5 Document Editing API Is Not Supported");
    }
    else
    {
        document.execCommand('styleWithCSS', false, true);
    }
}, false);

//underlines the selected text
function underline()
{
    document.execCommand("underline", false, null);
}

//makes the selected text as hyperlink.
function link()
{
    var url = prompt("Enter the URL");
    document.execCommand("createLink", false, url);
}

//displays HTML of the output
function displayhtml()
{
    //set textContent of pre tag to the innerHTML of editable div. textContent can take any form of text and display it as it is without browser interpreting it. It also preserves white space and new line characters.
    document.getElementsByClassName("htmloutput")[0].textContent = document.getElementsByClassName("editor")[0].innerHTML;
}
.editor
{
    width: 500px;
    height: 500px;
    background-color: yellow;
}
<button onclick="underline()">Underline Text</button>
<button onclick="link()">Link</button>
<button onclick="displayhtml()">Display HTML</button>
<!-- Make it content editable attribute true so that we can edit inside the div tag and also enable execCommand to edit content inside it.-->
<div class="editor" contenteditable="true" spellcheck="false">
    This is the text editor
</div>

<div class="codeoutput">
    <!-- <pre> tags reserves whitespace and newline characters. -->
    <pre class="htmloutput">
    </pre>
</div>

参考:labs.qnimate.com/wysiwyg-editor

所见即所得编辑器未内置于 Web 浏览器中。您将不得不使用库或自己编写一些代码。

您可以 a quick search on GitHub 找到 JavaScript 的所见即所得编辑器。

  • wysiwyg.js 看起来是个不错的开始
  • adamsanderson/wysiwyg 看起来像是 "starter kit"——也就是说,虽然它不具备您可能需要的所有功能,但它会让您自己动手
  • Aloha 是一款商业编辑器,看起来可以让您根据需要编辑整个页面

我还没有使用过这些,但这些似乎是开始的地方。