发布于2026-07-22 阅读(0)
扫一扫,手机访问
最近在解决数据粘贴方面取得了不少进展,这是HTML在线编辑器所必须具备的技术。这里详细给大家介绍整个过程,并提供实现参考。研究过程中确实走了不少弯路,尝试了多种方式——由于美国的PM始终觉得有些影响用户体验的东西无法接受,导致好几个提案被否掉,不过收获还是相当丰富的。
现在写代码喜欢需求驱动,先来看看这项技术的主要需求:
本例所适用的场景为使用iframe实现的HTML编辑器,而不是文本框(textarea或type为text的input)。
研究过程中,主要参考了TinyMCE和CKEditor,但最后选择了TinyMCE的实现方法,具体原因在看完下面这段文字后就会明白。
CKEditor的实现方式是在onpaste事件触发时,从剪贴板取出数据,处理取出的文本,然后再把处理好的文本存入剪贴板。有人可能会问:能不能在onpaste中直接取消paste动作,然后自己把获得的内容放入iframe当中?当时也试过这条路,但结果出人意料——直接从剪贴板拿出的数据是不包括格式信息的文本,特别是从Word粘贴过来的数据,纯文本,颜色、布局等数据都不存在。这样一来,用户只能粘贴没有格式的数据过来,然后自己重新在HTML编辑器里面编辑。但如果让浏览器自己去做粘贴,格式信息都会保留,浏览器会自动把Word的粘贴数据转换为XML数据,放入DOM中。所以为了保留格式信息,恐怕只能通过浏览器的标准粘贴行为的帮助来实现这一点。
另外,CKEditor在Firefox中有一个致命的弱点:如果你要从剪贴板读写数据,就必须提示用户自己去设置一个叫signed.applets.codebase_principal_support的权限,Ja vaScript脚本是没有权限去设置的。虽然从技术角度来看这是很正常的,但很多产品经理无法接受这一点——至少我遇到的PM是这么认为的。
以下是CKEditor获取和设置剪贴板的代码,供参考。
复制代码
function setClipboard(maintext) {
if (window.clipboardData) {
return (window.clipboardData.setData("Text", maintext));
}
else if (window.netscape) {
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
if (!clip) return;
var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
if (!trans) return;
trans.addDataFla vor('text/unicode');
var str = new Object();
var len = new Object();
var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
var copytext=maintext;
str.data=copytext;
trans.setTransferData("text/unicode",str,copytext.length*2);
var clipid=Components.interfaces.nsIClipboard;
if (!clip) return false;
clip.setData(trans,null,clipid.kGlobalClipboard);
return true;
}
return false;
}
function getClipboard() {
if (window.clipboardData) {
return(window.clipboardData.getData('Text'));
}
else if (window.netscape) {
netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
if (!clip) return;
var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
if (!trans) return;
trans.addDataFla vor('text/unicode');
clip.getData(trans,clip.kGlobalClipboard);
var str = new Object();
var len = new Object();
try {
trans.getTransferData('text/unicode',str,len);
}
catch(error) {
return null;
}
if (str) {
if (Components.interfaces.nsISupportsWString) str=str.value.QueryInterface(Components.interfaces.nsISupportsWString);
else if (Components.interfaces.nsISupportsString) str=str.value.QueryInterface(Components.interfaces.nsISupportsString);
else str = null;
}
if (str) {
return(str.data.substring(0,len.value / 2));
}
}
return null;
}
以下是提示用户启用权限的代码:
复制代码
if (window.netscape)
{
try
{
netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
}
catch (ex)
{
alert("If you want to do paste, please input 'about:config' in address bar, then input Enter.\n Set \"signed.applets.codebase_principal_support\" to \"true\"");
}
}
于是转向了TinyMCE的实现方式。在看它的代码时,特别留意到它竟然不需要权限就能在Firefox下面搞定粘贴,并且还能保留Word格式,于是仔细阅读了其中的逻辑。TinyMCE的实现步骤在IE和Firefox下面是不同的:
IE实现
document.execCommand(“paste”),内容会粘贴在临时的iframe中。(临时iframe可以根据个人喜好从DOM中删除,但由于这个iframe可以在多个HTML编辑器之间共用,所以实现中仅仅改变了iframe的left、top来调整iframe的位置,而不是移除它。调整left和top的目的在于:焦点移到临时iframe的时候,如果HTML编辑器的iframe和临时iframe不在一个视图之内,屏幕会滚动,这样会导致屏幕没有原因的闪烁。)
Firefox实现
window.setTimeout设置一个回调函数,在paste动作瞬间完成之后执行。inserthtml命令(execCommand(“inserthtml”))把过滤后的内容贴到HTML编辑器的iframe中。详细代码如下:
复制代码
function getSel(w)
{
return w.getSelection ? w.getSelection() : w.document.selection;
}
function setRange(sel,r)
{
sel.removeAllRanges();
sel.addRange(r);
}
function filterPasteData(originalText)
{
var newText=originalText;
//do something to filter unnecessary data
return newText;
}
function block(e)
{
e.preventDefault();
}
var w,or,divTemp,originText;
var newData;
function pasteClipboardData(editorId,e)
{
var objEditor = document.getElementById(editorId);
var edDoc=objEditor.contentWindow.document;
if(isIE)
{
var orRange=objEditor.contentWindow.document.selection.createRange();
var ifmTemp=document.getElementById("ifmTemp");
if(!ifmTemp)
{
ifmTemp=document.createElement("IFRAME");
ifmTemp.id="ifmTemp";
ifmTemp.style.width="1px";
ifmTemp.style.height="1px";
ifmTemp.style.position="absolute";
ifmTemp.style.border="none";
ifmTemp.style.left="-10000px";
ifmTemp.src="iframeblankpage.html";
document.body.appendChild(ifmTemp);
ifmTemp.contentWindow.document.designMode = "On";
ifmTemp.contentWindow.document.open();
ifmTemp.contentWindow.document.write("");
ifmTemp.contentWindow.document.close();
}else
{
ifmTemp.contentWindow.document.body.innerHTML="";
}
originText=objEditor.contentWindow.document.body.innerText;
ifmTemp.contentWindow.focus();
ifmTemp.contentWindow.document.execCommand("Paste",false,null);
objEditor.contentWindow.focus();
newData=ifmTemp.contentWindow.document.body.innerHTML;
//filter the pasted data
newData=filterPasteData(newData);
ifmTemp.contentWindow.document.body.innerHTML=newData;
//paste the data into the editor
orRange.pasteHTML(newData);
//block default paste
if(e)
{
e.returnValue = false;
if(e.preventDefault)
e.preventDefault();
}
return false;
}else
{
enableKeyDown=false;
//create the temporary html editor
var divTemp=edDoc.createElement("DIV");
divTemp.id='htmleditor_tempdiv';
divTemp.innerHTML='\uFEFF';
divTemp.style.left="-10000px"; //hide the div
divTemp.style.height="1px";
divTemp.style.width="1px";
divTemp.style.position="absolute";
divTemp.style.overflow="hidden";
edDoc.body.appendChild(divTemp);
//disable keyup,keypress, mousedown and keydown
objEditor.contentWindow.document.addEventListener("mousedown",block,false);
objEditor.contentWindow.document.addEventListener("keydown",block,false);
enableKeyDown=false;
//get current selection;
w=objEditor.contentWindow;
or=getSel(w).getRangeAt(0);
//move the cursor to into the div
var docBody=divTemp.firstChild;
rng = edDoc.createRange();
rng.setStart(docBody, 0);
rng.setEnd(docBody, 1);
setRange(getSel(w),rng);
originText=objEditor.contentWindow.document.body.textContent;
if(originText==='\uFEFF')
{
originText="";
}
window.setTimeout(function()
{
//get and filter the data after onpaste is done
if(divTemp.innerHTML==='\uFEFF')
{
newData="";
edDoc.body.removeChild(divTemp);
return;
}
newData=divTemp.innerHTML;
// Restore the old selection
if (or)
{
setRange(getSel(w),or);
}
newData=filterPasteData(newData);
divTemp.innerHTML=newData;
//paste the new data to the editor
objEditor.contentWindow.document.execCommand('inserthtml', false, newData );
edDoc.body.removeChild(divTemp);
},0);
//enable keydown,keyup,keypress, mousedown;
enableKeyDown=true;
objEditor.contentWindow.document.removeEventListener("mousedown",block,false);
objEditor.contentWindow.document.removeEventListener("keydown",block,false);
return true;
}
}
这里的pasteClipboardData是用作onpaste回调函数的。要使用它,可以通过下面的代码把它加到HTML编辑器的iframe的onpaste事件上。
复制代码
var ifrm=document.getElementById("editor")
if(isIE)
{
ifrm.contentWindow.document.documentElement.attachEvent("onpaste", function(e){return pasteClipboardData(ifrm.id,e);});
}
else
{
ifrm.contentWindow.document.addEventListener("paste", function(e){return pasteClipboardData(ifrm.id,e);},false);
}
这里的filterPasteData函数就是专门用来做过滤的函数,具体要怎么去过滤纯文本、HTML及Word数据,将在下一篇讲解。
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
8