防止 contenteditable 在 ENTER 上添加 <div> - Chrome

新手上路,请多包涵

我有一个 contenteditable 元素,每当我输入一些东西并点击 ENTER 它会创建一个新的 <div> 并将新行文本放在那里我有点不喜欢这个。

是否可以防止这种情况发生或至少用 <br> 替换它?

这是演示 http://jsfiddle.net/jDvau/

注意: 这在 Firefox 中不是问题。

原文由 iConnor 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 481
2 个回答

尝试这个:

 $('div[contenteditable]').keydown(function(e) {
    // trap the return key being pressed
    if (e.keyCode === 13) {
        // insert 2 br tags (if only one br tag is inserted the cursor won't go to the next line)
        document.execCommand('insertHTML', false, '<br/>');
        // prevent the default behaviour of return key pressed
        return false;
    }
});

单击此处进行演示

原文由 Ram G Athreya 发布,翻译遵循 CC BY-SA 4.0 许可协议

Add style display:inline-block; to contenteditable , it will not generate div , p and span automatically in Chrome.

原文由 Le Tung Anh 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题