最近做一个项目,需要实现web端的im聊天功能。考虑到执行效率不能用extjs,最后决定采用
jquery+div+css(没办法只有重新发明轮子了^_^)。个人一直比较反感js,感觉这门语言对开发人员太
不人性化,尤其在调试、兼容性等问题,简直是场灾难(呵呵,工作之余发下牢骚)。项目进行到现在,一般
功能实现也差不多了,回过头来对当初一些问题做个总结,留个名便于以后查询。该代码在ie6、ie7、firefox上测试通过。
一、html编辑器。
1.表情符插入:
对于这个功能在使用者看来实现是理所当然的事,但要自己实现却有2个难度:一是html textarea控件中并不支持html代码,即在textarea中使用<img src='...'>标签不会显示图片;二是在信息输入框输入文字的同时要支持表情符的任意插入,即在光标处插入表情。在网上查了很多资料,参考了extjs htmleditor源码,使用iframe方式总算把这问题搞定,以下是主要实现代码:
初始化htmleditor实现:
/*初始化htmleditor*/
function initInputHtmleditor(){
var iframeSrc = $.browser.msie? "javascript:false;" : "javascript:;";
var msgIndiv = '<IFRAME name="messageSend" id="messageSend" frameBorder="0" src="'+iframeSrc+'"></IFRAME>';
$('#msgInputDiv').html(msgIndiv);//把iframe加入到页面显示div中
/*通过div id获取iframe的document对象*/
var doc = getIframeDoc('messageSend');
doc.open();
doc.write(getDocMarkup());
doc.close();
$(doc).ready(function(){
doc.designMode="on";
//doc.contentEditable = true;
});
/*加载键盘触发事件*/
$(doc).bind('keypress',function(event){//添加处理事件
addSendMsg(event);
});
}
/*获取iframe document对象*/
function getIframeDoc(iframeId){
var iframeObj = $('#'+iframeId);
var wnd = getIframeWnd(iframeId);
var doc = $.browser.msie ? wnd.document : (iframeObj.contentDocument || wnd.document);
return doc;
}
/*获取iframe document window 对象*/
function getIframeWnd(iframeId){
return $.browser.msie ? document.frames(iframeId) : window.frames[iframeId];
}
/*
* 返回html document标志字符串
该方法中p元素的css margin和padding属性一定要设为0,否则ie下处理回车事件时行距会很大,因为ie在iframe下对回车是按<p></p>处理的*/
function getDocMarkup(){
return '<html><head><style type="text/css">' +
'body{border:0;margin:0px;padding:0px;height:98%;cursor:text;' +
'word-break:break-all;}' +//字体自动换行
'p{margin:0px;padding:0px;}' +
'</style></head><body></body></html>';
}
插入表情代码:
/*
* 在文档光标处插入文本
* 插入示例:
* var img = "<img src='"+basePath+"face/01.gif' ></img>";
* var doc = getIframeDoc('messageSend');//取iframe document对象
* insertAtCursor(doc,img,'messageSend');
* */
function insertAtCursor(doc,value,focusElId){
if($.browser.msie){//ie
var wnd = getIframeWnd(focusElId);//聚焦元素id
wnd.focus();
var r = doc.selection.createRange();
if(r){
r.collapse(true);
r.pasteHTML(value);
}
}else if($.browser.mozilla || $.browser.opera){//firefox ,opera
var wnd = getIframeWnd(focusElId);//聚焦元素id
wnd.focus();
doc.execCommand("InsertHTML", false, value === undefined ? null : value);
}else if($.browser.safari){//safari
doc.execCommand("InsertText", false, value === undefined ? null : value);
}
}