一、一些概念:
1、鼠标事件有一个botton属性:返回一个整数,用于表示点击的是哪个鼠标按键。
bug:在ie和标准dom的鼠标事件中,唯一一个button属性值相同的是“单击右键”事件,都返回2。
2、事件onmousedown:表示鼠标按键按下的动作。
事件oncontextmenu:点击鼠标触发的另一个事件。
3、中断默认事件处理函数的方法:ie中设置returnvalue=false; 标准dom中调用preventdefault()方法。
4、事件对象:①在ie中,事件对象是window对象的一个event属性。
声明:
②在标准dom中,事件对象是事件处理函数的唯一参数。
声明:
解决兼容性:
二、实现:
html:
复制代码 代码如下:
uncle cat is a fat white cat !
剪切
复制
粘贴
javascript:
复制代码 代码如下:
window.onload=function(){
rightmenu('p1','d1');
}
/****
* 封装右键菜单函数:
*elementid 要自定义右键菜单的 元素的id
*menuid 要显示的右键菜单div的 id
*/
function rightmenu(elementid,menuid){
var menu=document.getelementbyid(menuid); //获取菜单对象
var element=document.getelementbyid(elementid);//获取点击拥有自定义右键的 元素
element.onmousedown=function(aevent){ //设置该元素的 按下鼠标右键右键的 处理函数
if(window.event)aevent=window.event; //解决兼容性
if(aevent.button==2){ //当事件属性button的值为2时,表用户按下了右键
document.oncontextmenu=function(aevent){
if(window.event){
aevent=window.event;
aevent.returnvalue=false; //对ie 中断 默认点击右键事件处理函数
}else{
aevent.preventdefault(); //对标准dom 中断 默认点击右键事件处理函数
};
};
menu.style.csstext='display:block;top:'+aevent.clienty+'px;'+'left:'+aevent.clientx+'px;'
//将菜单相对 鼠标定位
}
}
menu.onmouseout=function(){ //设置 鼠标移出菜单时 隐藏菜单
settimeout(function(){menu.style.display=none;},400);
}
}