我将为html创建一个wysiwyg 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>
&#13;
1 w 帽子 y ou s ee i s w 帽子 y ou g et
答案 0 :(得分:5)
WYSIWYG编辑器未内置于Web浏览器中。您必须自己使用库或编写一些代码。
您可以a quick search on GitHub查找JavaScript的WYSIWYG编辑器。
我没有使用任何这些,但这些似乎是开始的地方。
答案 1 :(得分:1)
您可以使用以下代码......
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>