在InternetExplorer中,每次按Enter键时,contentEditable DIV会创建一个新的段落(<p></p>
),而Firefox会创建一个<br/>
标签。
是否有可能强制IE插入<br/>
而不是新段落?
在InternetExplorer中,每次按Enter键时,contentEditable DIV会创建一个新的段落(<p></p>
),而Firefox会创建一个<br/>
标签。
是否有可能强制IE插入<br/>
而不是新段落?
这里有一个解决方案(使用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);
}
window.event.stopPropagation();
)然后使用插入HTML命令来避免插入段落。但是,IE依赖于这些div来设置样式等,使用<br>会导致问题。您可以学习使用 SHIFT + ENTER 进行单行换行,ENTER 进行段落换行。IE在这方面的行为类似于MS Word。
更改可编辑的<div>
内部<p>
的line-height
有效:
#editable_div p
{
line-height: 0px;
}
insertNode()
替代pasteHTML()
,以实现 IE11+ 和跨浏览器的兼容性,具体情况参见 这里。 - svnm