iFrame 按回车键中断

iFrame break on enter key

我有一个用于创建消息的 iFrame。但是,当我在 iFrame 中键入时按回车键时,它会创建另一个 div,但是,我希望它创建一个 <br/>。我尝试使用 execCommand insertBrOnReturn,但我没有让它工作。有任何想法吗?提前致谢!

Whosebug 中的 JSFiddle 并没有真正起作用,但我在默认 jsfiddle.net 之后的 "Craz1k0ek/d869w67b/" 有一个现有的

function iFrameOn() {
    richTextField.document.designMode = 'On';
    richTextField.document.body.style.fontFamily = 'Open Sans,Helvetica Neue,Helvetica,Arial,sans-serif';
}
function iBold() {
    richTextField.document.execCommand('bold', false, null);
}
function iUnderline() {
    richTextField.document.execCommand('underline', false, null);
}
function iItalic() {
    richTextField.document.execCommand('italic', false, null);
}
function submit_form() {
    var theForm = document.getElementById("myForm");
    theForm.elements["myTextArea"].value = window.frames['richTextField'].document.body.innerHTML;
    theForm.submit();
}
<body onload="iFrameOn()">
  <form action="" name="myForm" id="myForm" method="post">
    <p>
      Title
      <input name="title" id="title" type="text" size="80" maxlength="80">
    </p>
    <div id="wysiwyg_cp" style="padding:8px; width:700px;">
      <input type="button" onClick="iBold()" value="B">
      <input type="button" onClick="iUnderline()" value="U">
      <input type="button" onClick="iItalic()" value="I">
    </div>
    <textarea style="display:none;" name="myTextArea" id="myTextArea" cols="100" rows="14"></textarea>
    <iframe name="richTextField" id="richTextField" style="border:#000 1px solid; width:700px; height:300px;"></iframe>
    <input name="myBtn" type="button" value="Submit Data" onClick="javascript:submit_form();">
  </form>
</body>

我把submit_form函数改成如下:

function submit_form() {
    remove_divs();
    var theForm = document.getElementById("myForm");
    theForm.elements["myTextArea"].value = window.frames['richTextField'].document.body.innerHTML;
    theForm.submit();
}

然后我添加了如下的remove_divs函数:

function remove_divs() {
    var frameHTML = window.frames['richTextField'].document.body.innerHTML;
    frameHTML = frameHTML
        .replace(/<div><br><\/div>/g, '')
        .replace(/<div>/g, '<p>')
        .replace(/<\/div>/g, '</p>');
    $(window.frames['richTextField'].document.body).html(frameHTML);
}

它将所有 <div><br></div> 元素替换为空,然后将所有 <div> 元素替换为 <p>,将所有 </div> 元素替换为 </p> .这完全按照我的需要格式化字段中的文本。

然后我在设置 DesignMode = 'On'; 时遇到问题我通过在 javascript 文件中放置额外的代码解决了这个问题,如下所示:

window.onload = function() {
    window.frames['richTextField'].document.designMode = "On";
}

我还收到了一些关于如何访问 richTextField 的小警告,因此我将所有 richTextField.document.execCommand 元素替换为 window.frames['richTextField'].document.execCommand

希望对您有所帮助!