当用户点击返回时,阻止Firefox创建一个新的contenteditable div

时间:2011-04-09 01:15:57

标签: html firefox contenteditable

我的网站上有一个令人满意的div,效果很好。

在Chrome上我可以使用返回键添加另一行。

在Firefox上,它会创建一个新的(额外的)div。

我知道我可以使用shift + return,但我不认为用户现在会这样:)

是否可以阻止此行为?

查看小提琴:http://jsfiddle.net/D7MJx/

我用FF 3.6尝试过它

编辑:在IE8上发生同样的事情

2 个答案:

答案 0 :(得分:2)

好的,我现在想出来了。

这不是最好的(阅读最干净的)解决方案,但它对我有用。

仅在Chrome上对此进行了测试,但我认为其他浏览器的工作原理相同。

我最终这样做了:

  $('div[contenteditable=true]').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 second line)
      document.execCommand('insertHTML', false, '<br><br>');
      // prevent the default behaviour of return key pressed
      return false;
    }
  });

答案 1 :(得分:0)

我想你想要insertBrOnReturn命令。

document.getElementById('myRichEditArea').contentDocument.execCommand('insertBrOnReturn',false, true)

https://developer.mozilla.org/en/rich-text_editing_in_mozilla

Mozilla文档说IE不支持insertBrOnReturn,但文档很旧,可能意味着IE7或更低版​​本。在IE中可能还有另一种方法。