ie是最早支持剪辑板相关事件(并且允许javascript接入)的浏览器(鼠标右键复制)

 
相关事件:
beforecopy— Fires just before the copy operation takes place.
copy— Fires when the copy operation takes place.
beforecut— Fires just before the cut operation takes place.
cut— Fires when the cut operation takes place.
beforepaste— Fires just before the paste operation takes place.
paste— Fires when the paste operation takes place.
 
因为这个标准是比较新的,所以浏览器之间差异还是有的( In Safari, Chrome, and Firefox, the beforecopy, beforecut, and beforepasteevents fire only when the context menu for the text box is displayed 
(in anticipation of a clipboard event), but Internet Explorer fires them in that case and immediately before firing the copy, cut, and pasteevents.)
 
 beforecopy, beforecut, 和 beforepaste让你有机会在发送或者读取剪辑板数据之前修改数据,但是取消这三个事件是不会取消复制,粘贴行为的,只有取消copy,cut,paste才能取消
 
剪辑板的数据可以通过clipboardData对象获取,在ie上为window属性,其他浏览器为event属性
该对象有三个方法:
getData():   获取剪辑板的数据,接收一参数(为读取数据的格式,ie为text或URL,其他浏览器接收一个MIME类型,text会识别为text/plain)
setData():  第一个参数同上为数据类型,第二个参数为需要保存的数据
clearData() :清除数据
 
兼容:
var EventUtil = {
   getClipboardText: function(event) {
       var clipboardData = (event.clipboardData || window.clipboardData);
       return clipboardData.getData(“text”);
    },
    setClipboardText: function(event, value){
       if (event.clipboardData){
              return event.clipboardData.setData(“text/plain”, value);
       } else if (window.clipboardData){
              return window.clipboardData.setData(“text”, value);
       }
    },
};
 
例子:当你某个输入框只允许数字
EventUtil.addHandler(textbox, “paste”, function(event){
});
Firefox, Safari, and Chrome 只有在paste事件才允许接入 getData()  方法
 
如果浏览器不支持的,例如opera,那么要屏蔽复制粘贴行为,就需要屏蔽复制粘贴等键盘操作和屏蔽右键弹出菜单(context menu)
 
HTML5有一个contextmenu事件,可以用来控制这个菜单怎么出现的,阻止默认菜单,用自己模仿的取代:
EventUtil.addHandler(window, “load”, function(event){
var div = document.getElementById(“myDiv”);
 
EventUtil.addHandler(div, “contextmenu”, function(event){
event = EventUtil.getEvent(event);
EventUtil.preventDefault(event);
 
var menu = document.getElementById(“myMenu”);       //自己用div做的菜单
menu.style.left = event.clientX + “px”;
menu.style.top = event.clientY + “px”;
menu.style.visibility = “visible”;
});
 
EventUtil.addHandler(document, “click”, function(event){
document.getElementById(“myMenu”).style.visibility = “hidden”;
});
});
05-02 20:53