2010-01-13 142 views

回答

7

是的,可以通过先停止keydown事件(window.event.stopPropagation();)然后使用插入HTML command插入字符串来避免插入段落。

但是,IE依赖于这个divs来设置样式等,你将会遇到麻烦,使用<br> s。

我建议你使用像TinyMCE or other editors这样的项目,然后搜索一个按你喜欢的方式工作的编辑器,因为它们针对不同的浏览器问题提供了各种解决方法。也许你可以找到它使用<BR>秒的编辑器...

+1

这一战略突破撤消。每次按Enter键,您都会修改DOM,因此用户不能再使用“撤消”菜单撤销更改! – 2010-02-08 10:40:06

+2

使用命令操作DOM不会破坏撤消。每个命令都可以撤消。当然,你必须避免像div.innerHTML =“foo”; – 2010-02-18 15:01:57

6

设置这里有一个解决方案(用了jQuery)。点击'更改为BR'按钮后,将插入<br>标签,而不是<p></p>标签。

HTML:

<div id='editable' contentEditable="true"> 
This is a division that is content editable. You can position the cursor 
within the text, move the cursor with the arrow keys, and use the keyboard 
to enter or delete text at the cursor position. 
</div> 
<button type="button" onclick='InsertBR()'>Change to BR</button> 
<button type="button" onclick='ViewSource()'>View Div source</button> 

的Javascript:

function InsertBR() 
{ 
    $("#editable").keypress(function(e) { 
     if (e.which == 13) 
     { 
      e.preventDefault(); 
      document.selection.createRange().pasteHTML("<br/>")  
     } 
    }); 
} 

function ViewSource() 
{   
    var div = document.getElementById('editable'); 
    alert('div.innerHTML = ' + div.innerHTML); 
} 

Theselinkshelped。 工作示例here

+1

使用'insertNode()'而不是'pasteHTML()'为IE11 +和跨浏览器提到[这里](http://stackoverflow.com/questions/6690752/insert-html-at-caret-in-a- contenteditable -div/6691294#6691294) – 2015-10-21 00:33:00

5

你总是可以学会使用SHIFT + ENTER 一行回报和ENTER段落的回报。 IE在这方面的行为与MS Word相似。

1

更改编辑<div>作品里面<p>line-height

#editable_div p 
{ 
    line-height: 0px; 
}