Javascript实现web编辑器-兼容FF和IE

Posted on 2008-04-15 19:08  三体星  阅读(1738)  评论(0编辑  收藏  举报

背景: CREAT需要进行文本分析,主要的任务就是从一大段原始需求文本中,通过人工或者自动的手段,识别出有用的元素,并打上标记。 由于自然文本的任意性,用自动的方法无法完全精确地得出文本的处理结果,即使是人工处理,也往往需要进行几轮迭代式的分析处理。 Web编辑器即使设计来支持人工处理的这一过程的。

实现说明:

IFrame作为编辑器主体。

设置一下iframe的属性,iframe即可作为编辑器了。

<iframe frameborder="0" id="WebEditor" style="border: 1px dashed black;
height: 320px; width: 760px"
></iframe>
<script language="javascript">
Editor 
= document.getElementById("WebEditor").contentWindow;
Editor.document.designMode 
= "on";//使document处于可编辑状态
Editor.document.open();
//For FF, 打开新的document以便编辑新内容
//Editor.document.write("");//可以设置header信息等, Iframe可以看成一个独立的html页面
Editor.document.close();//关闭document,强制发送数据显示
</script>

Javascript处理文本格式

调用execCommand函数处理文本,可以实现粗斜下划、对齐方式、超链接、字体(大小、颜色等功能) execCommand函数的语法:

bSuccess = object . execCommand ( sCommand , bUserInterface , vValue )

    document.execCommand() 解析


function format(what, opt)
{
    Editor.focus();
    Editor.document.execCommand(what, 
false, opt);
}

识别选择的文本,操纵DOM

这里有几个FF和IE不同的地方,一个是回车,IE下是<p>,比FF的<br/>空了很多,解决方法是重载编辑器document的回车事件:

Editor.document.onkeypress = fnKeypress;
function fnKeypress(){
    
if(document.all){
        
var ev = Editor.event;
        
if(ev.keyCode==13 && !ev.shiftKey){//判断回车键
            var s = Editor.document.selection;
            
if (s!=null){
                
var r = s.createRange();
                
if (r!=null{
                    r.pasteHTML(
"<BR/>");
                    r.select();
//将光标移动到新行
                }

            }

            
return false;
        }

    }

}

处理选择的文本:

function message()
{
    
if(document.all)//如果是 IE. (虽然,FF也可以用document.all)
    alert(Editor.document.selection.createRange().text);
    
else{
        
//alert(Editor.document.getSelection());
        alert(Editor.getSelection());
        
var selection = Editor.getSelection().getRangeAt(0);
        
var linkElement = Editor.document.createElement("a"); //创建一个新的<A>节点
        linkElement.href = "http://asers.blog.sohu.com";//设置<A>节点的href属性
        selection.surroundContents(linkElement);//加入超链接
    }

}

插入html代码:


function insert(html)
{
    
debugger;
    
if(window.event)
    Editor.document.selection.createRange().pasteHTML(html);
    
else
    format(
"insertHTML", html);
}

Demo:

web编辑器demo

参考:

IE和Firefox 对于相同的源代码解析有所有不同

JS的IE和FF兼容性问题的汇总小结

Gecko DOM Reference

Copyright © 2024 三体星
Powered by .NET 8.0 on Kubernetes