0

我正在为应用程序创建一个简单的 RTE,它不需要太复杂,所以我认为使用 execCommands 可能是最好的解决方案。但是,我遇到了麻烦,因为这些命令创建了无效的 HTML。这是我正在使用的javascript,任何对造成这种情况的原因的见解将不胜感激。

    $('.turnEditOn').live('click',function(){
        richTextEditor.document.designMode = 'ON';
        $('#richTextEditor').focus();   });
    $('#bold').live('click',function(){
        richTextEditor.document.execCommand('bold',false,null);
        $('#richTextEditor').focus();   });
    $('#underline').live('click',function(){
        richTextEditor.document.execCommand('underline',false,null);
        $('#richTextEditor').focus();   });
    $('#italic').live('click',function(){
        richTextEditor.document.execCommand('italic',false,null);
        $('#richTextEditor').focus();   });
4

1 回答 1

0

HTML:

<div id="turnEditOn" class="command">on</div>
<div id="bold" class="command"><b>B</b></div>
<div id="italic" class="command"><i>I</i></div>
<div id="underline" class="command"><u>U</u></div>
<div class="command" onclick="alert(document.getElementById('richTextEditor').contentDocument.body.innerHTML);">Show HTML</div>
<br/>
<iframe id="richTextEditor" style="width:500px;height:300px;"></iframe>

JAVASCRIPT+jQuery(onDomReady):

var richTextEditor=document.getElementById("richTextEditor");
$('#turnEditOn').live('click',function(){
    richTextEditor.contentDocument.designMode = 'ON';
    richTextEditor.contentDocument.body.contentEditable=true;
    // Switch FireFox RTE execCommand engine to work in same manner as IE
    try{richTextEditor.contentDocument.execCommand('styleWithCSS',false,false);}
    catch(e){}
    richTextEditor.focus();
});
$('#bold').live('click',function(){
    richTextEditor.contentDocument.execCommand('bold',false,null);
    richTextEditor.focus();
});
$('#underline').live('click',function(){
    richTextEditor.contentDocument.execCommand('underline',false,null);
    richTextEditor.focus();
});
$('#italic').live('click',function(){
    richTextEditor.contentDocument.execCommand('italic',false,null);
    richTextEditor.focus();
});

示例:http: //jsfiddle.net/d2L2A/

阅读MDN 中的富文本编辑

于 2012-05-04T06:19:29.777 回答