html 元素只出现在 space 之后

html elements only appear after space

我正在使用 Javascript 的 onkeyup 事件将在 contenteditable div 中输入的文本输入到输入字段中。

当用户输入 div 时,他们可以选择将所选文本设为粗体或斜体 (这是通过突出显示所需文本并单击其中一个按钮来完成的) .

如何使 html 标签自动出现在单词周围而无需按空格键?

<form method="post">
<button type="button" id="bold"><b>B</b></button>
<button type="button" id="italic"><i>I</i></button>
<div id="post" style="border: 1px solid;" contenteditable></div>
<input type="text" name="hiddenTextarea" id="hiddenTextarea">
<input type="submit">
</form>

<script>
$(document).ready(function() {
  $('#bold').click(function() {
    document.execCommand('bold');
  });
});

$(document).ready(function() {
  $('#italic').click(function() {
    document.execCommand('italic');
  });
});

var contentText = document.getElementById('post');
var hiddenInput = document.getElementById('hiddenTextarea');

// copy the text to input when the user writes in contentText div
contentText.onkeyup = function() {
    hiddenInput.value = this.innerHTML;  // 'this' is pointing to contentText
};
</script>

这是一个 JsFiddle,您可以自己查看问题:https://jsfiddle.net/u6oeu9dL/1/

我建议您将 class 名称注入 div#post 而不是 execCommand

.bold { font-weight: bold; }
.italic { font-style: italic; }

输入仅在 keyup 时更新,您应该将更新输入的代码移动到命名函数,以便您可以在 keyup 和单击样式按钮时调用它。

$(document).ready(function() {
  $('#bold').click(function() {
    document.execCommand('bold');
    updateInput();
  });
});

$(document).ready(function() {
  $('#italic').click(function() {
    document.execCommand('italic');
    updateInput();
  });
});

var contentText = document.getElementById('post');
var hiddenInput = document.getElementById('hiddenTextarea');

function updateInput () {
  hiddenInput.value = contentText.innerHTML
}

// copy the text to input when the user writes in contentText div
contentText.onkeyup = updateInput;

https://jsfiddle.net/u6oeu9dL/5/ (简体)