简单的html编辑器,并使用div或textarea获取html内容

时间:2019-03-08 21:27:37

标签: javascript jquery html contenteditable

尝试创建一个简单的html编辑器。

$('#edit').on('input', function(e){
	console.log($(this).html());
});
.edit{
background:gold;
min-height:140px;
font-size:1.6em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='edit' id='edit' contenteditable></div>

在div edit内键入:

lorem
ipsum

然后将光标置于lorem的末尾-并按键盘上的spacebardel以获取此信息:

lorem ipsum

您会看到问题-ipsum的字体大小比lorem大。

这是第一个问题-如何避免这种情况?

我的第二次尝试是使用textarea而不是contenteditable div,但是在那种情况下,我无法使用document.execCommand将某些文本更改为bold等。

那么如何像在textareastackoverflow网站上这样在wordpress内设置html标签呢?

我的最终目标是提供仅需几个命令的简单编辑器-bold, italic and align用户应该能够键入和设置文本样式,然后单击按钮即可获取html内容。

有帮助吗?

2 个答案:

答案 0 :(得分:1)

正如许多愤怒的开发人员所指出的那样,contenteditable确实是可怕的-别指望有什么好事,但是无论如何,让我们尝试做吧。

通过将可编辑div包裹在另一个div中并将CSS字体应用于此包装器,在执行问题中所述的过程时,文本不会变大。 HTML仍然很丑陋(字体大小为1em的无用的span标签),但是文本内容是可以接受的。

const editable = document.querySelector('div[contenteditable]');

editable.onkeyup = () => {
  document.querySelector('#html-log').innerText = editable.innerHTML;
  document.querySelector('#text-log').innerText = JSON.stringify(editable.innerText);
}
#wrapper {
  font-size: 1.2em;
}
div[contenteditable] {
  width: 100%;
  height: 100%;
  border: solid;
  font-size: 1em;
}
<div id="wrapper">
  <div contenteditable></div>
</div>

<h3>HTML content</h3>
<pre id="html-log"></pre>

<h3>Text content</h3>
<pre id="text-log"></pre>

答案 1 :(得分:0)

.execCommand()

通过分配每个#id的{​​{1}}来匹配命令来尝试动态加载第一个参数。

<button>

演示

<button id="bold">B</button>
...
... var ID = this.id;
return document.execCommand(ID, false, null)
$('#WYSINWYE').on('submit', function() {
  return false;
});
$('#edit').focus();
$('#edit').on('keyup', function() {
  $('#view').html($(this).text());
});
$('#ctrl button').on('click', function() {
  var ID = this.id;
  if (ID === 'HTML') {
    $('#view').slideToggle('750')
    return;
  }
  return document.execCommand(ID, false, null);
});
form {
  width: 100%;
  height: fit-content;
  font: 400 16px/1.25 Arial;
}

#view {
  background: gold;
  min-height: 100px;
  font: inherit;
  border-top-left-radius: 6px;
  border-top-right-radius: 6px;
}

#ctrl {
  height: 20px;
}

#edit {
  font: inherit;
  font-family: Consolas;
  border-bottom-left-radius: 6px;
  border-bottom-right-radius: 6px;
}

button {
  display: inline-block;
  font: inherit;
  width: 36px;
  height: 24px;
  line-height: 24px;
  margin: 0 -2px;
  vertical-align: middle;
  cursor: pointer;
  border-radius: 1px;
}

b:hover,
button:hover {
  color: rgba(205, 121, 0, 0.8);
}

#HTML {
  float: right
}

#ctrl button:first-of-type {
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
}

#ctrl button:nth-of-type(6) {
  border-top-right-radius: 4px;
  border-bottom-right-radius: 4px;
}

#ctrl button:last-of-type {
  border-radius: 4px;
}