避免ie contentEditable元素在Enter键上创建段落

Fra*_*ger 10 html contenteditable

在InternetExplorer上,<p></p>每次按Enter键时,contentEditable DIV都会创建一个新段落(),而Firefox会创建一个<br/>标记.是否可以强制IE插入<br/>而不是新段落?

Jon*_*eiß 7

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

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

我建议您使用像TinyMCE或其他编辑器这样的项目,并搜索一个行为符合您希望的编辑器,因为它们针对不同的浏览器问题提供了各种解决方法.也许你可以找到一个使用<br>的编辑器......

  • 使用命令操作DOM不会破坏撤消.每个命令都可以撤消.当然你必须避免像div.innerHTML ="foo"这样的东西; (2认同)

ros*_*533 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>
Run Code Online (Sandbox Code Playgroud)

使用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);
}
Run Code Online (Sandbox Code Playgroud)

这些 链接有 帮助.这里的工作示例.


Fen*_*ton 5

您始终可以学习使用SHIFT+ ENTER进行单行返回和ENTER段落返回.IE在这方面表现得像MS Word.