【问题标题】:html elements only appear after spacehtml元素只出现在空格之后
【发布时间】:2016-05-19 18:44:58
【问题描述】:

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

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

  • 如果用户在 div 中输入“hello”并将文本加粗,它将在输入字段中显示为hello(单词周围没有<br> 标签)。
  • 如果用户在 div 中输入“hello”并将文本加粗,然后按空格键,它将在输入字段中显示为<b>hello</b>

如何使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/

【问题讨论】:

    标签: javascript jquery html contenteditable


    【解决方案1】:

    输入仅在 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/(简体)

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-07-18
        • 2019-06-17
        • 1970-01-01
        相关资源
        最近更新 更多