contentEditable - Firefox <br /> tag

只谈情不闲聊 提交于 2019-12-18 04:54:06

问题


Firefox inserts a <br /> tag on press enter whereas the other browsers are adding either a <p> or <div>. I know that chrome and safari are inserting the same tag of the firstchild of the contentEditable div. So do Firefox, however, if the first tag's innerHTML is empty firefox is just ignoring the tag and creating a new line by pushing the default node in the second line and writes directly inside the editor instead of inside a child node. So basically, I want Firefox to write inside the given tag and continue to insert that kind of node on each press on enter. How can it be done? Any suggestions?


回答1:


I've found the solution :) In order to make this work, you've to give an id to the caret's parent element. Then you can use the following code. Please note that I get the browsernName from c# and put it into a hidden field. That's why I equaled it to "firefox". The following code is tested with FF 3.6 and it works perfectly. The only thing is that you'll have to check the caret's parent element and if it is not equal to the current row's id, then you'll have to place the caret inside the current row by using a selection function. Also, perform this code on the keyup event and make sure that if you perform some other codes on the keyup event, put this code at the end of it! Anways, enjoy :)

// 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 == "") ? "&#8203;" : 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 = "&#8203;";
    }
}



回答2:


Try inserting a <p></p> inside your element. Then almost certainly every newline will be a new paragraph.



来源:https://stackoverflow.com/questions/5705580/contenteditable-firefox-br-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!