Sha*_*kan 9 javascript firefox enter contenteditable
Firefox <br />在按下输入时插入标记,而其他浏览器添加a <p>或<div>.我知道chrome和safari正在插入contentEditable div的第一个孩子的相同标签.但是,Firefox也是如此,如果第一个标签的innerHTML是空的,那么firefox只是忽略标签并通过推送第二行中的默认节点创建一个新行,并直接在编辑器内部而不是在子节点内部写入.所以基本上,我希望Firefox在给定标签内写入并继续在每次按下时插入那种节点.怎么做到呢?有什么建议?
我找到了解决方案:) 为了使这项工作有效,您必须为插入符的父元素提供一个 id。然后你可以使用下面的代码。请注意,我从 c# 获取 browsernName 并将其放入隐藏字段中。这就是为什么我将其等同于“firefox”。以下代码在FF 3.6上测试,完美运行。唯一的事情是,您必须检查脱字符号的父元素,如果它不等于当前行的 id,那么您必须使用选择函数将脱字符号放置在当前行内。另外,在 keyup 事件上执行此代码,并确保如果您在 keyup 事件上执行其他一些代码,请将此代码放在其末尾!无论如何,享受吧:)
// The code works good in the following cases:
// 1) If there is text inside the editor and the user selects the whole text
// and replace it with a single character, the <p> tag will be placed and the
// text will place inside the p tag
// 2) If the user selects the whole code and deletes it and begins to type again
// 3) If the user types normally and press enter
// NB: Please note me if you find any bug
if (browserName == "firefox") {
//remove all br tags
var brs = txteditor.getElementsByTagName("br");
for (var i = 0; i < brs.length; i++) { brs[i].parentNode.removeChild(brs[i]); }
//check whether there is a p tag inside
var para = txteditor.getElementsByTagName("p");
if (para.length == 0) {
var inner = txteditor.innerHTML.replace(/^\s+|\s+$/g, '');
var str = (inner == "") ? "​" : txteditor.innerHTML;
var nText = "<p id=\"" + cRow + "\">" + str + "</p>";
// in order to prevent a dublicate row clear inside the text editor
txteditor.innerHTML = "";
document.execCommand('insertHTML', false, nText);
} else {
// always make sure that the current row's innerHTML is never empty
if (document.getElementById(cRow).innerHTML == "")
document.getElementById(cRow).innerHTML = "​";
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8075 次 |
| 最近记录: |